/[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 53 by schoenebeck, Mon Apr 26 17:15:51 2004 UTC revision 620 by schoenebeck, Wed Jun 8 23:16:13 2005 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003 by Benno Senoner and Christian Schoenebeck         *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005 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 "lscpserver.h"  #include "lscpserver.h"
25    #include "lscpresultset.h"
26    #include "lscpevent.h"
27    //#include "../common/global.h"
28    
29    #include <fcntl.h>
30    
31    #if HAVE_SQLITE3
32    # include "sqlite3.h"
33    #endif
34    
35    #include "../engines/EngineFactory.h"
36    #include "../drivers/audio/AudioOutputDeviceFactory.h"
37    #include "../drivers/midi/MidiInputDeviceFactory.h"
38    
39  #include "../engines/gig/Engine.h"  /**
40     * Below are a few static members of the LSCPServer class.
41     * The big assumption here is that LSCPServer is going to remain a singleton.
42     * These members are used to support client connections.
43     * Class handles multiple connections at the same time using select() and non-blocking recv()
44     * Commands are processed by a single LSCPServer thread.
45     * Notifications are delivered either by the thread that originated them
46     * or (if the resultset is currently in progress) by the LSCPServer thread
47     * after the resultset was sent out.
48     * This makes sure that resultsets can not be interrupted by notifications.
49     * This also makes sure that the thread sending notification is not blocked
50     * by the LSCPServer thread.
51     */
52    fd_set LSCPServer::fdSet;
53    int LSCPServer::currentSocket = -1;
54    std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
55    std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
56    std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
57    std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
58    Mutex LSCPServer::NotifyMutex = Mutex();
59    Mutex LSCPServer::NotifyBufferMutex = Mutex();
60    Mutex LSCPServer::SubscriptionMutex = Mutex();
61    Mutex LSCPServer::RTNotifyMutex = Mutex();
62    
63  LSCPServer::LSCPServer(Sampler* pSampler) : Thread(false, 0, -4) {  LSCPServer::LSCPServer(Sampler* pSampler) : Thread(true, false, 0, -4) {
64      this->pSampler = pSampler;      this->pSampler = pSampler;
65        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");
66        LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");
67        LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
68        LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
69        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
70        LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
71        hSocket = -1;
72    }
73    
74    LSCPServer::~LSCPServer() {
75        if (hSocket >= 0) close(hSocket);
76    }
77    
78    /**
79     * Blocks the calling thread until the LSCP Server is initialized and
80     * accepting socket connections, if the server is already initialized then
81     * this method will return immediately.
82     * @param TimeoutSeconds     - optional: max. wait time in seconds
83     *                             (default: 0s)
84     * @param TimeoutNanoSeconds - optional: max wait time in nano seconds
85     *                             (default: 0ns)
86     * @returns  0 on success, a value less than 0 if timeout exceeded
87     */
88    int LSCPServer::WaitUntilInitialized(long TimeoutSeconds, long TimeoutNanoSeconds) {
89        return Initialized.WaitAndUnlockIf(false, TimeoutSeconds, TimeoutNanoSeconds);
90  }  }
91    
92  int LSCPServer::Main() {  int LSCPServer::Main() {
# Line 41  int LSCPServer::Main() { Line 102  int LSCPServer::Main() {
102      SocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);      SocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);
103    
104      if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {      if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
105          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...";
106          close(hSocket);          for (int trial = 0; true; trial++) { // retry for LSCP_SERVER_BIND_TIMEOUT seconds
107          //return -1;              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
108          exit(EXIT_FAILURE);                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
109                        std::cerr << "gave up!" << std::endl;
110                        close(hSocket);
111                        //return -1;
112                        exit(EXIT_FAILURE);
113                    }
114                    else sleep(1); // sleep 1s
115                }
116                else break; // success
117            }
118      }      }
119    
120      listen(hSocket, 1);      listen(hSocket, 1);
121      dmsg(1,("LSCPServer: Server running.\n")); // server running      Initialized.Set(true);
122    
123      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
124      sockaddr_in client;      sockaddr_in client;
125      int length = sizeof(client);      int length = sizeof(client);
126        FD_ZERO(&fdSet);
127        FD_SET(hSocket, &fdSet);
128        int maxSessions = hSocket;
129    
130      while (true) {      while (true) {
131          hSession = accept(hSocket, (sockaddr*) &client, (socklen_t*) &length);          fd_set selectSet = fdSet;
132          if (hSession < 0) {          int retval = select(maxSessions+1, &selectSet, NULL, NULL, NULL);
133              std::cerr << "LSCPServer: Client connection failed." << std::endl;          if (retval == 0)
134              close(hSocket);                  continue; //Nothing try again
135              //return -1;          if (retval == -1) {
136              exit(EXIT_FAILURE);                  std::cerr << "LSCPServer: Socket select error." << std::endl;
137          }                  close(hSocket);
138                    exit(EXIT_FAILURE);
139          dmsg(1,("LSCPServer: Client connection established.\n"));          }
140          //send(hSession, "Welcome!\r\n", 10, 0);  
141            //Accept new connections now (if any)
142          // Parser invocation          if (FD_ISSET(hSocket, &selectSet)) {
143          yyparse_param_t yyparse_param;                  int socket = accept(hSocket, (sockaddr*) &client, (socklen_t*) &length);
144          yyparse_param.pServer = this;                  if (socket < 0) {
145          yylex_init(&yyparse_param.pScanner);                          std::cerr << "LSCPServer: Client connection failed." << std::endl;
146          while (yyparse(&yyparse_param) == LSCP_SYNTAX_ERROR); // recall parser in case of syntax error                          exit(EXIT_FAILURE);
147          yylex_destroy(yyparse_param.pScanner);                  }
148    
149                    if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
150                            std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
151                            exit(EXIT_FAILURE);
152                    }
153    
154                    // Parser initialization
155                    yyparse_param_t yyparse_param;
156                    yyparse_param.pServer  = this;
157                    yyparse_param.hSession = socket;
158    
159                    Sessions.push_back(yyparse_param);
160                    FD_SET(socket, &fdSet);
161                    if (socket > maxSessions)
162                            maxSessions = socket;
163                    dmsg(1,("LSCPServer: Client connection established on socket:%d.\n", socket));
164                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection established on socket", socket));
165                    continue; //Maybe this was the only selected socket, better select again
166            }
167    
168            //Something was selected and it was not the hSocket, so it must be some command(s) coming.
169            for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {
170                    if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?
171                            if (GetLSCPCommand(iter)) {     //Have we read the entire command?
172                                    dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));
173                                    int dummy; // just a temporary hack to fulfill the restart() function prototype
174                                    restart(NULL, dummy); // restart the 'scanner'
175                                    currentSocket = (*iter).hSession;  //a hack
176                                    dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
177                                    if ((*iter).bVerbose) { // if echo mode enabled
178                                        AnswerClient(bufferedCommands[currentSocket]);
179                                    }
180                                    int result = yyparse(&(*iter));
181                                    currentSocket = -1;     //continuation of a hack
182                                    dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
183                                    if (result == LSCP_QUIT) { //Was it a quit command by any chance?
184                                            CloseConnection(iter);
185                                    }
186                            }
187                            //socket may have been closed, iter may be invalid, get out of the loop for now.
188                            //we'll be back if there is data.
189                            break;
190                    }
191            }
192    
193            //Now let's deliver late notifies (if any)
194            NotifyBufferMutex.Lock();
195            for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
196                    send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
197                    bufferedNotifies.erase(iterNotify);
198            }
199            NotifyBufferMutex.Unlock();
200        }
201    }
202    
203    void LSCPServer::CloseConnection( std::vector<yyparse_param_t>::iterator iter ) {
204            int socket = (*iter).hSession;
205            dmsg(1,("LSCPServer: Client connection terminated on socket:%d.\n",socket));
206            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
207            Sessions.erase(iter);
208            FD_CLR(socket,  &fdSet);
209            SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)
210            for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {
211                    iter->second.remove(socket);
212            }
213            SubscriptionMutex.Unlock();
214            NotifyMutex.Lock();
215            bufferedCommands.erase(socket);
216            bufferedNotifies.erase(socket);
217            close(socket);
218            NotifyMutex.Unlock();
219    }
220    
221    int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
222            int subs = 0;
223            SubscriptionMutex.Lock();
224            for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();
225                            iter != events.end(); iter++)
226            {
227                    subs += eventSubscriptions.count(*iter);
228            }
229            SubscriptionMutex.Unlock();
230            return subs;
231    }
232    
233    void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
234            SubscriptionMutex.Lock();
235            if (eventSubscriptions.count(event.GetType()) == 0) {
236                    SubscriptionMutex.Unlock();     //Nobody is subscribed to this event
237                    return;
238            }
239            std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
240            std::list<int>::iterator end = eventSubscriptions[event.GetType()].end();
241            String notify = event.Produce();
242    
243            while (true) {
244                    if (NotifyMutex.Trylock()) {
245                            for(;iter != end; iter++)
246                                    send(*iter, notify.c_str(), notify.size(), 0);
247                            NotifyMutex.Unlock();
248                            break;
249                    } else {
250                            if (NotifyBufferMutex.Trylock()) {
251                                    for(;iter != end; iter++)
252                                            bufferedNotifies[*iter] += notify;
253                                    NotifyBufferMutex.Unlock();
254                                    break;
255                            }
256                    }
257            }
258            SubscriptionMutex.Unlock();
259    }
260    
261    extern int GetLSCPCommand( void *buf, int max_size ) {
262            String command = LSCPServer::bufferedCommands[LSCPServer::currentSocket];
263            if (command.size() == 0) {              //Parser wants input but we have nothing.
264                    strcpy((char*) buf, "\n");      //So give it an empty command
265                    return 1;                       //to keep it happy.
266            }
267    
268            if (max_size < command.size()) {
269                    std::cerr << "getLSCPCommand: Flex buffer too small, ignoring the command." << std::endl;
270                    return 0;       //This will never happen
271            }
272    
273            strcpy((char*) buf, command.c_str());
274            LSCPServer::bufferedCommands.erase(LSCPServer::currentSocket);
275            return command.size();
276    }
277    
278          close(hSession);  /**
279          dmsg(1,("LSCPServer: Client connection terminated.\n"));   * Will be called to try to read the command from the socket
280      }   * If command is read, it will return true. Otherwise false is returned.
281     * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.
282     */
283    bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {
284            int socket = (*iter).hSession;
285            char c;
286            int i = 0;
287            while (true) {
288                    int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
289                    if (result == 0) { //socket was selected, so 0 here means client has closed the connection
290                            CloseConnection(iter);
291                            break;
292                    }
293                    if (result == 1) {
294                            if (c == '\r')
295                                    continue; //Ignore CR
296                            if (c == '\n') {
297                                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
298                                    bufferedCommands[socket] += "\n";
299                                    return true; //Complete command was read
300                            }
301                            bufferedCommands[socket] += c;
302                    }
303                    if (result == -1) {
304                            if (errno == EAGAIN) //Would block, try again later.
305                                    return false;
306                            switch(errno) {
307                                    case EBADF:
308                                            dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
309                                            break;
310                                    case ECONNREFUSED:
311                                            dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
312                                            break;
313                                    case ENOTCONN:
314                                            dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));
315                                            break;
316                                    case ENOTSOCK:
317                                            dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
318                                            break;
319                                    case EAGAIN:
320                                            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"));
321                                            break;
322                                    case EINTR:
323                                            dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
324                                            break;
325                                    case EFAULT:
326                                            dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
327                                            break;
328                                    case EINVAL:
329                                            dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
330                                            break;
331                                    case ENOMEM:
332                                            dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
333                                            break;
334                                    default:
335                                            dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
336                                            break;
337                            }
338                            CloseConnection(iter);
339                            break;
340                    }
341            }
342            return false;
343  }  }
344    
345  /**  /**
# Line 85  int LSCPServer::Main() { Line 350  int LSCPServer::Main() {
350   */   */
351  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
352      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));
353      send(hSession, ReturnMessage.c_str(), ReturnMessage.size(), 0);      if (currentSocket != -1) {
354                NotifyMutex.Lock();
355                send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
356                NotifyMutex.Unlock();
357        }
358    }
359    
360    /**
361     * Find a created audio output device index.
362     */
363    int LSCPServer::GetAudioOutputDeviceIndex ( AudioOutputDevice *pDevice )
364    {
365        // Search for the created device to get its index
366        std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
367        std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
368        for (; iter != devices.end(); iter++) {
369            if (iter->second == pDevice)
370                return iter->first;
371        }
372        // Not found.
373        return -1;
374    }
375    
376    /**
377     * Find a created midi input device index.
378     */
379    int LSCPServer::GetMidiInputDeviceIndex ( MidiInputDevice *pDevice )
380    {
381        // Search for the created device to get its index
382        std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
383        std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
384        for (; iter != devices.end(); iter++) {
385            if (iter->second == pDevice)
386                return iter->first;
387        }
388        // Not found.
389        return -1;
390    }
391    
392    String LSCPServer::CreateAudioOutputDevice(String Driver, std::map<String,String> Parameters) {
393        dmsg(2,("LSCPServer: CreateAudioOutputDevice(Driver=%s)\n", Driver.c_str()));
394        LSCPResultSet result;
395        try {
396            AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);
397            // search for the created device to get its index
398            int index = GetAudioOutputDeviceIndex(pDevice);
399            if (index == -1) throw LinuxSamplerException("Internal error: could not find created audio output device.");
400            result = index; // success
401        }
402        catch (LinuxSamplerException e) {
403            result.Error(e);
404        }
405        return result.Produce();
406    }
407    
408    String LSCPServer::CreateMidiInputDevice(String Driver, std::map<String,String> Parameters) {
409        dmsg(2,("LSCPServer: CreateMidiInputDevice(Driver=%s)\n", Driver.c_str()));
410        LSCPResultSet result;
411        try {
412            MidiInputDevice* pDevice = pSampler->CreateMidiInputDevice(Driver, Parameters);
413            // search for the created device to get its index
414            int index = GetMidiInputDeviceIndex(pDevice);
415            if (index == -1) throw LinuxSamplerException("Internal error: could not find created midi input device.");
416            result = index; // success
417        }
418        catch (LinuxSamplerException e) {
419            result.Error(e);
420        }
421        return result.Produce();
422    }
423    
424    String LSCPServer::DestroyAudioOutputDevice(uint DeviceIndex) {
425        dmsg(2,("LSCPServer: DestroyAudioOutputDevice(DeviceIndex=%d)\n", DeviceIndex));
426        LSCPResultSet result;
427        try {
428            std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
429            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
430            AudioOutputDevice* pDevice = devices[DeviceIndex];
431            pSampler->DestroyAudioOutputDevice(pDevice);
432        }
433        catch (LinuxSamplerException e) {
434            result.Error(e);
435        }
436        return result.Produce();
437    }
438    
439    String LSCPServer::DestroyMidiInputDevice(uint DeviceIndex) {
440        dmsg(2,("LSCPServer: DestroyMidiInputDevice(DeviceIndex=%d)\n", DeviceIndex));
441        LSCPResultSet result;
442        try {
443            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
444            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
445            MidiInputDevice* pDevice = devices[DeviceIndex];
446            pSampler->DestroyMidiInputDevice(pDevice);
447        }
448        catch (LinuxSamplerException e) {
449            result.Error(e);
450        }
451        return result.Produce();
452  }  }
453    
454  /**  /**
455   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
456   */   */
457  String LSCPServer::LoadInstrument(String Filename, uint uiInstrument, uint uiSamplerChannel) {  String LSCPServer::LoadInstrument(String Filename, uint uiInstrument, uint uiSamplerChannel, bool bBackground) {
458      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));
459      result_t result;      LSCPResultSet result;
460      try {      try {
461          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
462          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
463          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
464          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw LinuxSamplerException("No engine type assigned to sampler channel yet");
465          pEngine->LoadInstrument(Filename.c_str(), uiInstrument);          if (!pSamplerChannel->GetAudioOutputDevice())
466          result.type = result_type_success;              throw LinuxSamplerException("No audio output device connected to sampler channel");
467            if (bBackground) {
468                InstrumentLoader.StartNewLoad(Filename, uiInstrument, pEngineChannel);
469            }
470            else {
471                // tell the engine channel which instrument to load
472                pEngineChannel->PrepareLoadInstrument(Filename.c_str(), uiInstrument);
473                // actually start to load the instrument (blocks until completed)
474                pEngineChannel->LoadInstrument();
475            }
476      }      }
477      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
478           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
479      }      }
480      return ConvertResult(result);      return result.Produce();
481  }  }
482    
483  /**  /**
484   * 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
485     * sampler channel.
486   */   */
487  String LSCPServer::LoadEngine(String EngineName, uint uiSamplerChannel) {  String LSCPServer::SetEngineType(String EngineName, uint uiSamplerChannel) {
488      dmsg(2,("LSCPServer: LoadEngine(EngineName=%s,SamplerChannel=%d)\n", EngineName.c_str(), uiSamplerChannel));      dmsg(2,("LSCPServer: LoadEngine(EngineName=%s,SamplerChannel=%d)\n", EngineName.c_str(), uiSamplerChannel));
489      result_t result;      LSCPResultSet result;
490      try {      try {
         engine_type_t type;  
         if (EngineName == "gig") type = engine_type_gig;  
         else throw LinuxSamplerException("Unknown engine type");  
491          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
492          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
493          pSamplerChannel->LoadEngine(type);          LockRTNotify();
494          result.type = result_type_success;          pSamplerChannel->SetEngineType(EngineName);
495            UnlockRTNotify();
496      }      }
497      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
498           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
499      }      }
500      return ConvertResult(result);      return result.Produce();
501  }  }
502    
503  /**  /**
# Line 140  String LSCPServer::LoadEngine(String Eng Line 505  String LSCPServer::LoadEngine(String Eng
505   */   */
506  String LSCPServer::GetChannels() {  String LSCPServer::GetChannels() {
507      dmsg(2,("LSCPServer: GetChannels()\n"));      dmsg(2,("LSCPServer: GetChannels()\n"));
508      return ToString(pSampler->SamplerChannels()) + "\r\n";      LSCPResultSet result;
509        result.Add(pSampler->SamplerChannels());
510        return result.Produce();
511    }
512    
513    /**
514     * Will be called by the parser to get the list of sampler channels.
515     */
516    String LSCPServer::ListChannels() {
517        dmsg(2,("LSCPServer: ListChannels()\n"));
518        String list;
519        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
520        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
521        for (; iter != channels.end(); iter++) {
522            if (list != "") list += ",";
523            list += ToString(iter->first);
524        }
525        LSCPResultSet result;
526        result.Add(list);
527        return result.Produce();
528  }  }
529    
530  /**  /**
# Line 149  String LSCPServer::GetChannels() { Line 533  String LSCPServer::GetChannels() {
533  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
534      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
535      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();
536      return "OK[" + ToString(pSamplerChannel->Index()) + "]\r\n";      LSCPResultSet result(pSamplerChannel->Index());
537        return result.Produce();
538  }  }
539    
540  /**  /**
# Line 157  String LSCPServer::AddChannel() { Line 542  String LSCPServer::AddChannel() {
542   */   */
543  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
544      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
545        LSCPResultSet result;
546        LockRTNotify();
547      pSampler->RemoveSamplerChannel(uiSamplerChannel);      pSampler->RemoveSamplerChannel(uiSamplerChannel);
548      return "OK\r\n";      UnlockRTNotify();
549        return result.Produce();
550  }  }
551    
552  /**  /**
553   * 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.
554   */   */
555  String LSCPServer::GetAvailableEngines() {  String LSCPServer::GetAvailableEngines() {
556      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));
557      return "gig\r\n";      LSCPResultSet result("1");
558        return result.Produce();
559  }  }
560    
561  /**  /**
562   * Will be called by the parser to get descriptions for a particular engine.   * Will be called by the parser to get a list of all available engines.
563     */
564    String LSCPServer::ListAvailableEngines() {
565        dmsg(2,("LSCPServer: ListAvailableEngines()\n"));
566        LSCPResultSet result("\'GIG\'");
567        return result.Produce();
568    }
569    
570    /**
571     * Will be called by the parser to get descriptions for a particular
572     * sampler engine.
573   */   */
574  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
575      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
576      result_t result;      LSCPResultSet result;
577      try {      try {
578          if (EngineName == "gig") {          Engine* pEngine = EngineFactory::Create(EngineName);
579              Engine* pEngine = new LinuxSampler::gig::Engine;          result.Add("DESCRIPTION", pEngine->Description());
580              String info = pEngine->Description() + "\r\n";          result.Add("VERSION",     pEngine->Version());
581              delete pEngine;          delete pEngine;
             return info; // success  
         }  
         else throw LinuxSamplerException("Unknown engine type");  
582      }      }
583      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
584           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
585      }      }
586      return ConvertResult(result);      return result.Produce();
587  }  }
588    
589  /**  /**
# Line 199  String LSCPServer::GetEngineInfo(String Line 592  String LSCPServer::GetEngineInfo(String
592   */   */
593  String LSCPServer::GetChannelInfo(uint uiSamplerChannel) {  String LSCPServer::GetChannelInfo(uint uiSamplerChannel) {
594      dmsg(2,("LSCPServer: GetChannelInfo(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetChannelInfo(SamplerChannel=%d)\n", uiSamplerChannel));
595      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
596        try {
597            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
598            if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
599            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
600    
601            //Defaults values
602            String EngineName = "NONE";
603            float Volume = 0.0f;
604            String InstrumentFileName = "NONE";
605            String InstrumentName = "NONE";
606            int InstrumentIndex = -1;
607            int InstrumentStatus = -1;
608            int AudioOutputChannels = 0;
609            String AudioRouting;
610    
611            if (pEngineChannel) {
612                EngineName          = pEngineChannel->EngineName();
613                AudioOutputChannels = pEngineChannel->Channels();
614                Volume              = pEngineChannel->Volume();
615                InstrumentStatus    = pEngineChannel->InstrumentStatus();
616                InstrumentIndex     = pEngineChannel->InstrumentIndex();
617                if (InstrumentIndex != -1) {
618                    InstrumentFileName = pEngineChannel->InstrumentFileName();
619                    InstrumentName     = pEngineChannel->InstrumentName();
620                }
621                for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
622                    if (AudioRouting != "") AudioRouting += ",";
623                    AudioRouting += ToString(pEngineChannel->OutputChannel(chan));
624                }
625            }
626    
627            result.Add("ENGINE_NAME", EngineName);
628            result.Add("VOLUME", Volume);
629    
630            //Some not-so-hardcoded stuff to make GUI look good
631            result.Add("AUDIO_OUTPUT_DEVICE", GetAudioOutputDeviceIndex(pSamplerChannel->GetAudioOutputDevice()));
632            result.Add("AUDIO_OUTPUT_CHANNELS", AudioOutputChannels);
633            result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
634    
635            result.Add("MIDI_INPUT_DEVICE", GetMidiInputDeviceIndex(pSamplerChannel->GetMidiInputDevice()));
636            result.Add("MIDI_INPUT_PORT", pSamplerChannel->GetMidiInputPort());
637            if (pSamplerChannel->GetMidiInputChannel() == MidiInputPort::midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
638            else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
639    
640            result.Add("INSTRUMENT_FILE", InstrumentFileName);
641            result.Add("INSTRUMENT_NR", InstrumentIndex);
642            result.Add("INSTRUMENT_NAME", InstrumentName);
643            result.Add("INSTRUMENT_STATUS", InstrumentStatus);
644        }
645        catch (LinuxSamplerException e) {
646             result.Error(e);
647        }
648        return result.Produce();
649  }  }
650    
651  /**  /**
# Line 208  String LSCPServer::GetChannelInfo(uint u Line 654  String LSCPServer::GetChannelInfo(uint u
654   */   */
655  String LSCPServer::GetVoiceCount(uint uiSamplerChannel) {  String LSCPServer::GetVoiceCount(uint uiSamplerChannel) {
656      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
657      result_t result;      LSCPResultSet result;
658      try {      try {
659          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
660          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
661          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
662          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw LinuxSamplerException("No engine loaded on sampler channel");
663          return ToString(pEngine->VoiceCount()) + "\r\n"; // success          if (!pEngineChannel->GetEngine()) throw LinuxSamplerException("No audio output device connected to sampler channel");
664            result.Add(pEngineChannel->GetEngine()->VoiceCount());
665      }      }
666      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
667           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
668      }      }
669      return ConvertResult(result);      return result.Produce();
670  }  }
671    
672  /**  /**
# Line 231  String LSCPServer::GetVoiceCount(uint ui Line 675  String LSCPServer::GetVoiceCount(uint ui
675   */   */
676  String LSCPServer::GetStreamCount(uint uiSamplerChannel) {  String LSCPServer::GetStreamCount(uint uiSamplerChannel) {
677      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
678      result_t result;      LSCPResultSet result;
679      try {      try {
680          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
681          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
682          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
683          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw LinuxSamplerException("No engine type assigned to sampler channel");
684          return ToString(pEngine->DiskStreamCount()) + "\r\n"; // success          if (!pEngineChannel->GetEngine()) throw LinuxSamplerException("No audio output device connected to sampler channel");
685            result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
686      }      }
687      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
688           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
689      }      }
690      return ConvertResult(result);      return result.Produce();
691  }  }
692    
693  /**  /**
# Line 254  String LSCPServer::GetStreamCount(uint u Line 696  String LSCPServer::GetStreamCount(uint u
696   */   */
697  String LSCPServer::GetBufferFill(fill_response_t ResponseType, uint uiSamplerChannel) {  String LSCPServer::GetBufferFill(fill_response_t ResponseType, uint uiSamplerChannel) {
698      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
699      result_t result;      LSCPResultSet result;
700      try {      try {
701          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
702          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
703          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
704          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw LinuxSamplerException("No engine type assigned to sampler channel");
705          if (!pEngine->DiskStreamSupported()) return "NA\r\n";          if (!pEngineChannel->GetEngine()) throw LinuxSamplerException("No audio output device connected to sampler channel");
706          switch (ResponseType) {          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
707              case fill_response_bytes:          else {
708                  return ToString(pEngine->DiskStreamBufferFillBytes()) + "\r\n"; // success              switch (ResponseType) {
709              case fill_response_percentage:                  case fill_response_bytes:
710                  return ToString(pEngine->DiskStreamBufferFillPercentage()) + "\r\n"; // success                      result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillBytes());
711              default:                      break;
712                  throw LinuxSamplerException("Unknown fill response type");                  case fill_response_percentage:
713                        result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillPercentage());
714                        break;
715                    default:
716                        throw LinuxSamplerException("Unknown fill response type");
717                }
718            }
719        }
720        catch (LinuxSamplerException e) {
721             result.Error(e);
722        }
723        return result.Produce();
724    }
725    
726    String LSCPServer::GetAvailableAudioOutputDrivers() {
727        dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));
728        LSCPResultSet result;
729        try {
730            int n = AudioOutputDeviceFactory::AvailableDrivers().size();
731            result.Add(n);
732        }
733        catch (LinuxSamplerException e) {
734            result.Error(e);
735        }
736        return result.Produce();
737    }
738    
739    String LSCPServer::ListAvailableAudioOutputDrivers() {
740        dmsg(2,("LSCPServer: ListAvailableAudioOutputDrivers()\n"));
741        LSCPResultSet result;
742        try {
743            String s = AudioOutputDeviceFactory::AvailableDriversAsString();
744            result.Add(s);
745        }
746        catch (LinuxSamplerException e) {
747            result.Error(e);
748        }
749        return result.Produce();
750    }
751    
752    String LSCPServer::GetAvailableMidiInputDrivers() {
753        dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));
754        LSCPResultSet result;
755        try {
756            int n = MidiInputDeviceFactory::AvailableDrivers().size();
757            result.Add(n);
758        }
759        catch (LinuxSamplerException e) {
760            result.Error(e);
761        }
762        return result.Produce();
763    }
764    
765    String LSCPServer::ListAvailableMidiInputDrivers() {
766        dmsg(2,("LSCPServer: ListAvailableMidiInputDrivers()\n"));
767        LSCPResultSet result;
768        try {
769            String s = MidiInputDeviceFactory::AvailableDriversAsString();
770            result.Add(s);
771        }
772        catch (LinuxSamplerException e) {
773            result.Error(e);
774        }
775        return result.Produce();
776    }
777    
778    String LSCPServer::GetMidiInputDriverInfo(String Driver) {
779        dmsg(2,("LSCPServer: GetMidiInputDriverInfo(Driver=%s)\n",Driver.c_str()));
780        LSCPResultSet result;
781        try {
782            result.Add("DESCRIPTION", MidiInputDeviceFactory::GetDriverDescription(Driver));
783            result.Add("VERSION",     MidiInputDeviceFactory::GetDriverVersion(Driver));
784    
785            std::map<String,DeviceCreationParameter*> parameters = MidiInputDeviceFactory::GetAvailableDriverParameters(Driver);
786            if (parameters.size()) { // if there are parameters defined for this driver
787                String s;
788                std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
789                for (;iter != parameters.end(); iter++) {
790                    if (s != "") s += ",";
791                    s += iter->first;
792                }
793                result.Add("PARAMETERS", s);
794          }          }
795      }      }
796      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
797           e.PrintMessage();          result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
798      }      }
799      return ConvertResult(result);      return result.Produce();
800  }  }
801    
802  /**  String LSCPServer::GetAudioOutputDriverInfo(String Driver) {
803   * Will be called by the parser to change the audio output type on a      dmsg(2,("LSCPServer: GetAudioOutputDriverInfo(Driver=%s)\n",Driver.c_str()));
804   * particular sampler channel.      LSCPResultSet result;
  */  
 String LSCPServer::SetAudioOutputType(audio_output_type_t AudioOutputType, uint uiSamplerChannel) {  
     dmsg(2,("LSCPServer: SetAudioOutputType(AudioOutputType=%d, SamplerChannel=%d)\n", AudioOutputType, uiSamplerChannel));  
     result_t result;  
805      try {      try {
806          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          result.Add("DESCRIPTION", AudioOutputDeviceFactory::GetDriverDescription(Driver));
807          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          result.Add("VERSION",     AudioOutputDeviceFactory::GetDriverVersion(Driver));
808          pSamplerChannel->SetAudioOutputDevice(AudioOutputType);  
809          result.type = result_type_success;          std::map<String,DeviceCreationParameter*> parameters = AudioOutputDeviceFactory::GetAvailableDriverParameters(Driver);
810            if (parameters.size()) { // if there are parameters defined for this driver
811                String s;
812                std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
813                for (;iter != parameters.end(); iter++) {
814                    if (s != "") s += ",";
815                    s += iter->first;
816                }
817                result.Add("PARAMETERS", s);
818            }
819      }      }
820      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
821           e.PrintMessage();          result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
822      }      }
823      return ConvertResult(result);      return result.Produce();
824    }
825    
826    String LSCPServer::GetMidiInputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
827        dmsg(2,("LSCPServer: GetMidiInputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size()));
828        LSCPResultSet result;
829        try {
830            DeviceCreationParameter* pParameter = MidiInputDeviceFactory::GetDriverParameter(Driver, Parameter);
831            result.Add("TYPE",         pParameter->Type());
832            result.Add("DESCRIPTION",  pParameter->Description());
833            result.Add("MANDATORY",    pParameter->Mandatory());
834            result.Add("FIX",          pParameter->Fix());
835            result.Add("MULTIPLICITY", pParameter->Multiplicity());
836            optional<String> oDepends       = pParameter->Depends();
837            optional<String> oDefault       = pParameter->Default(DependencyList);
838            optional<String> oRangeMin      = pParameter->RangeMin(DependencyList);
839            optional<String> oRangeMax      = pParameter->RangeMax(DependencyList);
840            optional<String> oPossibilities = pParameter->Possibilities(DependencyList);
841            if (oDepends)       result.Add("DEPENDS",       *oDepends);
842            if (oDefault)       result.Add("DEFAULT",       *oDefault);
843            if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
844            if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
845            if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
846        }
847        catch (LinuxSamplerException e) {
848            result.Error(e);
849        }
850        return result.Produce();
851    }
852    
853    String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
854        dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size()));
855        LSCPResultSet result;
856        try {
857            DeviceCreationParameter* pParameter = AudioOutputDeviceFactory::GetDriverParameter(Driver, Parameter);
858            result.Add("TYPE",         pParameter->Type());
859            result.Add("DESCRIPTION",  pParameter->Description());
860            result.Add("MANDATORY",    pParameter->Mandatory());
861            result.Add("FIX",          pParameter->Fix());
862            result.Add("MULTIPLICITY", pParameter->Multiplicity());
863            optional<String> oDepends       = pParameter->Depends();
864            optional<String> oDefault       = pParameter->Default(DependencyList);
865            optional<String> oRangeMin      = pParameter->RangeMin(DependencyList);
866            optional<String> oRangeMax      = pParameter->RangeMax(DependencyList);
867            optional<String> oPossibilities = pParameter->Possibilities(DependencyList);
868            if (oDepends)       result.Add("DEPENDS",       *oDepends);
869            if (oDefault)       result.Add("DEFAULT",       *oDefault);
870            if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
871            if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
872            if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
873        }
874        catch (LinuxSamplerException e) {
875            result.Error(e);
876        }
877        return result.Produce();
878    }
879    
880    String LSCPServer::GetAudioOutputDeviceCount() {
881        dmsg(2,("LSCPServer: GetAudioOutputDeviceCount()\n"));
882        LSCPResultSet result;
883        try {
884            uint count = pSampler->AudioOutputDevices();
885            result.Add(count); // success
886        }
887        catch (LinuxSamplerException e) {
888            result.Error(e);
889        }
890        return result.Produce();
891    }
892    
893    String LSCPServer::GetMidiInputDeviceCount() {
894        dmsg(2,("LSCPServer: GetMidiInputDeviceCount()\n"));
895        LSCPResultSet result;
896        try {
897            uint count = pSampler->MidiInputDevices();
898            result.Add(count); // success
899        }
900        catch (LinuxSamplerException e) {
901            result.Error(e);
902        }
903        return result.Produce();
904    }
905    
906    String LSCPServer::GetAudioOutputDevices() {
907        dmsg(2,("LSCPServer: GetAudioOutputDevices()\n"));
908        LSCPResultSet result;
909        try {
910            String s;
911            std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
912            std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
913            for (; iter != devices.end(); iter++) {
914                if (s != "") s += ",";
915                s += ToString(iter->first);
916            }
917            result.Add(s);
918        }
919        catch (LinuxSamplerException e) {
920            result.Error(e);
921        }
922        return result.Produce();
923    }
924    
925    String LSCPServer::GetMidiInputDevices() {
926        dmsg(2,("LSCPServer: GetMidiInputDevices()\n"));
927        LSCPResultSet result;
928        try {
929            String s;
930            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
931            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
932            for (; iter != devices.end(); iter++) {
933                if (s != "") s += ",";
934                s += ToString(iter->first);
935            }
936            result.Add(s);
937        }
938        catch (LinuxSamplerException e) {
939            result.Error(e);
940        }
941        return result.Produce();
942    }
943    
944    String LSCPServer::GetAudioOutputDeviceInfo(uint DeviceIndex) {
945        dmsg(2,("LSCPServer: GetAudioOutputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));
946        LSCPResultSet result;
947        try {
948            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
949            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
950            AudioOutputDevice* pDevice = devices[DeviceIndex];
951            result.Add("DRIVER", pDevice->Driver());
952            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
953            std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
954            for (; iter != parameters.end(); iter++) {
955                result.Add(iter->first, iter->second->Value());
956            }
957        }
958        catch (LinuxSamplerException e) {
959            result.Error(e);
960        }
961        return result.Produce();
962    }
963    
964    String LSCPServer::GetMidiInputDeviceInfo(uint DeviceIndex) {
965        dmsg(2,("LSCPServer: GetMidiInputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));
966        LSCPResultSet result;
967        try {
968            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
969            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
970            MidiInputDevice* pDevice = devices[DeviceIndex];
971            result.Add("DRIVER", pDevice->Driver());
972            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
973            std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
974            for (; iter != parameters.end(); iter++) {
975                result.Add(iter->first, iter->second->Value());
976            }
977        }
978        catch (LinuxSamplerException e) {
979            result.Error(e);
980        }
981        return result.Produce();
982    }
983    String LSCPServer::GetMidiInputPortInfo(uint DeviceIndex, uint PortIndex) {
984        dmsg(2,("LSCPServer: GetMidiInputPortInfo(DeviceIndex=%d, PortIndex=%d)\n",DeviceIndex, PortIndex));
985        LSCPResultSet result;
986        try {
987            // get MIDI input device
988            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
989            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
990            MidiInputDevice* pDevice = devices[DeviceIndex];
991    
992            // get MIDI port
993            MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
994            if (!pMidiInputPort) throw LinuxSamplerException("There is no MIDI input port with index " + ToString(PortIndex) + ".");
995    
996            // return the values of all MIDI port parameters
997            std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
998            std::map<String,DeviceRuntimeParameter*>::iterator iter = parameters.begin();
999            for (; iter != parameters.end(); iter++) {
1000                result.Add(iter->first, iter->second->Value());
1001            }
1002        }
1003        catch (LinuxSamplerException e) {
1004            result.Error(e);
1005        }
1006        return result.Produce();
1007    }
1008    
1009    String LSCPServer::GetAudioOutputChannelInfo(uint DeviceId, uint ChannelId) {
1010        dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%d,ChannelId)\n",DeviceId,ChannelId));
1011        LSCPResultSet result;
1012        try {
1013            // get audio output device
1014            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1015            if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");
1016            AudioOutputDevice* pDevice = devices[DeviceId];
1017    
1018            // get audio channel
1019            AudioChannel* pChannel = pDevice->Channel(ChannelId);
1020            if (!pChannel) throw LinuxSamplerException("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1021    
1022            // return the values of all audio channel parameters
1023            std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1024            std::map<String,DeviceRuntimeParameter*>::iterator iter = parameters.begin();
1025            for (; iter != parameters.end(); iter++) {
1026                result.Add(iter->first, iter->second->Value());
1027            }
1028        }
1029        catch (LinuxSamplerException e) {
1030            result.Error(e);
1031        }
1032        return result.Produce();
1033    }
1034    
1035    String LSCPServer::GetMidiInputPortParameterInfo(uint DeviceId, uint PortId, String ParameterName) {
1036        dmsg(2,("LSCPServer: GetMidiInputPortParameterInfo(DeviceId=%d,PortId=%d,ParameterName=%s)\n",DeviceId,PortId,ParameterName.c_str()));
1037        LSCPResultSet result;
1038        try {
1039            // get MIDI input device
1040            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1041            if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no midi input device with index " + ToString(DeviceId) + ".");
1042            MidiInputDevice* pDevice = devices[DeviceId];
1043    
1044            // get midi port
1045            MidiInputPort* pPort = pDevice->GetPort(PortId);
1046            if (!pPort) throw LinuxSamplerException("Midi input device does not have port " + ToString(PortId) + ".");
1047    
1048            // get desired port parameter
1049            std::map<String,DeviceRuntimeParameter*> parameters = pPort->PortParameters();
1050            if (!parameters.count(ParameterName)) throw LinuxSamplerException("Midi port does not provide a parameter '" + ParameterName + "'.");
1051            DeviceRuntimeParameter* pParameter = parameters[ParameterName];
1052    
1053            // return all fields of this audio channel parameter
1054            result.Add("TYPE",         pParameter->Type());
1055            result.Add("DESCRIPTION",  pParameter->Description());
1056            result.Add("FIX",          pParameter->Fix());
1057            result.Add("MULTIPLICITY", pParameter->Multiplicity());
1058            if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
1059            if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
1060            if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
1061        }
1062        catch (LinuxSamplerException e) {
1063            result.Error(e);
1064        }
1065        return result.Produce();
1066    }
1067    
1068    String LSCPServer::GetAudioOutputChannelParameterInfo(uint DeviceId, uint ChannelId, String ParameterName) {
1069        dmsg(2,("LSCPServer: GetAudioOutputChannelParameterInfo(DeviceId=%d,ChannelId=%d,ParameterName=%s)\n",DeviceId,ChannelId,ParameterName.c_str()));
1070        LSCPResultSet result;
1071        try {
1072            // get audio output device
1073            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1074            if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");
1075            AudioOutputDevice* pDevice = devices[DeviceId];
1076    
1077            // get audio channel
1078            AudioChannel* pChannel = pDevice->Channel(ChannelId);
1079            if (!pChannel) throw LinuxSamplerException("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1080    
1081            // get desired audio channel parameter
1082            std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1083            if (!parameters.count(ParameterName)) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParameterName + "'.");
1084            DeviceRuntimeParameter* pParameter = parameters[ParameterName];
1085    
1086            // return all fields of this audio channel parameter
1087            result.Add("TYPE",         pParameter->Type());
1088            result.Add("DESCRIPTION",  pParameter->Description());
1089            result.Add("FIX",          pParameter->Fix());
1090            result.Add("MULTIPLICITY", pParameter->Multiplicity());
1091            if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
1092            if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
1093            if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
1094        }
1095        catch (LinuxSamplerException e) {
1096            result.Error(e);
1097        }
1098        return result.Produce();
1099    }
1100    
1101    String LSCPServer::SetAudioOutputChannelParameter(uint DeviceId, uint ChannelId, String ParamKey, String ParamVal) {
1102        dmsg(2,("LSCPServer: SetAudioOutputChannelParameter(DeviceId=%d,ChannelId=%d,ParamKey=%s,ParamVal=%s)\n",DeviceId,ChannelId,ParamKey.c_str(),ParamVal.c_str()));
1103        LSCPResultSet result;
1104        try {
1105            // get audio output device
1106            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1107            if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");
1108            AudioOutputDevice* pDevice = devices[DeviceId];
1109    
1110            // get audio channel
1111            AudioChannel* pChannel = pDevice->Channel(ChannelId);
1112            if (!pChannel) throw LinuxSamplerException("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1113    
1114            // get desired audio channel parameter
1115            std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1116            if (!parameters.count(ParamKey)) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParamKey + "'.");
1117            DeviceRuntimeParameter* pParameter = parameters[ParamKey];
1118    
1119            // set new channel parameter value
1120            pParameter->SetValue(ParamVal);
1121        }
1122        catch (LinuxSamplerException e) {
1123            result.Error(e);
1124        }
1125        return result.Produce();
1126    }
1127    
1128    String LSCPServer::SetAudioOutputDeviceParameter(uint DeviceIndex, String ParamKey, String ParamVal) {
1129        dmsg(2,("LSCPServer: SetAudioOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1130        LSCPResultSet result;
1131        try {
1132            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1133            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
1134            AudioOutputDevice* pDevice = devices[DeviceIndex];
1135            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1136            if (!parameters.count(ParamKey)) throw LinuxSamplerException("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1137            parameters[ParamKey]->SetValue(ParamVal);
1138        }
1139        catch (LinuxSamplerException e) {
1140            result.Error(e);
1141        }
1142        return result.Produce();
1143    }
1144    
1145    String LSCPServer::SetMidiInputDeviceParameter(uint DeviceIndex, String ParamKey, String ParamVal) {
1146        dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1147        LSCPResultSet result;
1148        try {
1149            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1150            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1151            MidiInputDevice* pDevice = devices[DeviceIndex];
1152            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1153            if (!parameters.count(ParamKey)) throw LinuxSamplerException("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1154            parameters[ParamKey]->SetValue(ParamVal);
1155        }
1156        catch (LinuxSamplerException e) {
1157            result.Error(e);
1158        }
1159        return result.Produce();
1160    }
1161    
1162    String LSCPServer::SetMidiInputPortParameter(uint DeviceIndex, uint PortIndex, String ParamKey, String ParamVal) {
1163        dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1164        LSCPResultSet result;
1165        try {
1166            // get MIDI input device
1167            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1168            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1169            MidiInputDevice* pDevice = devices[DeviceIndex];
1170    
1171            // get MIDI port
1172            MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1173            if (!pMidiInputPort) throw LinuxSamplerException("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1174    
1175            // set port parameter value
1176            std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1177            if (!parameters.count(ParamKey)) throw LinuxSamplerException("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");
1178            parameters[ParamKey]->SetValue(ParamVal);
1179        }
1180        catch (LinuxSamplerException e) {
1181            result.Error(e);
1182        }
1183        return result.Produce();
1184  }  }
1185    
1186  /**  /**
1187   * Will be called by the parser to change the audio output channel for   * Will be called by the parser to change the audio output channel for
1188   * playback on a particular sampler channel.   * playback on a particular sampler channel.
1189   */   */
1190  String LSCPServer::SetAudioOutputChannel(uint AudioOutputChannel, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputChannel(uint ChannelAudioOutputChannel, uint AudioOutputDeviceInputChannel, uint uiSamplerChannel) {
1191      dmsg(2,("LSCPServer: SetAudioOutputChannel(AudioOutputChannel=%d, SamplerChannel=%d)\n", AudioOutputChannel, uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudioOutputChannel(ChannelAudioOutputChannel=%d, AudioOutputDeviceInputChannel=%d, SamplerChannel=%d)\n",ChannelAudioOutputChannel,AudioOutputDeviceInputChannel,uiSamplerChannel));
1192      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
1193        try {
1194            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1195            if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1196            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1197            if (!pEngineChannel) throw LinuxSamplerException("No engine type yet assigned to sampler channel " + ToString(uiSamplerChannel));
1198            if (!pSamplerChannel->GetAudioOutputDevice()) throw LinuxSamplerException("No audio output device connected to sampler channel " + ToString(uiSamplerChannel));
1199            pEngineChannel->SetOutputChannel(ChannelAudioOutputChannel, AudioOutputDeviceInputChannel);
1200        }
1201        catch (LinuxSamplerException e) {
1202             result.Error(e);
1203        }
1204        return result.Produce();
1205  }  }
1206    
1207  String LSCPServer::SetMIDIInputType(midi_input_type_t MidiInputType, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1208      dmsg(2,("LSCPServer: SetMIDIInputType(MidiInputType=%d, SamplerChannel=%d)\n", MidiInputType, uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1209      result_t result;      LSCPResultSet result;
1210      try {      try {
1211          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1212          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1213          pSamplerChannel->SetMidiInputDevice(MidiInputType);          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1214          result.type = result_type_success;          if (!devices.count(AudioDeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(AudioDeviceId));
1215            AudioOutputDevice* pDevice = devices[AudioDeviceId];
1216            pSamplerChannel->SetAudioOutputDevice(pDevice);
1217      }      }
1218      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
1219           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
1220      }      }
1221      return ConvertResult(result);      return result.Produce();
1222  }  }
1223    
1224  /**  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1225   * Will be called by the parser to change the MIDI input port on which the      dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1226   * engine of a particular sampler channel should listen to.      LSCPResultSet result;
1227   */      try {
1228  String LSCPServer::SetMIDIInputPort(String MIDIInputPort, uint uiSamplerchannel) {          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1229      dmsg(2,("LSCPServer: SetMIDIInputPort(MIDIInputPort=%s, Samplerchannel=%d)\n", MIDIInputPort.c_str(), uiSamplerchannel));          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1230      return "ERR:0:Not implemented yet.\r\n";          // Driver type name aliasing...
1231            if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1232            if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1233            // Check if there's one audio output device already created
1234            // for the intended audio driver type (AudioOutputDriver)...
1235            AudioOutputDevice *pDevice = NULL;
1236            std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1237            std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1238            for (; iter != devices.end(); iter++) {
1239                if ((iter->second)->Driver() == AudioOutputDriver) {
1240                    pDevice = iter->second;
1241                    break;
1242                }
1243            }
1244            // If it doesn't exist, create a new one with default parameters...
1245            if (pDevice == NULL) {
1246                std::map<String,String> params;
1247                pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1248            }
1249            // Must have a device...
1250            if (pDevice == NULL)
1251                throw LinuxSamplerException("Internal error: could not create audio output device.");
1252            // Set it as the current channel device...
1253            pSamplerChannel->SetAudioOutputDevice(pDevice);
1254        }
1255        catch (LinuxSamplerException e) {
1256             result.Error(e);
1257        }
1258        return result.Produce();
1259    }
1260    
1261    String LSCPServer::SetMIDIInputPort(uint MIDIPort, uint uiSamplerChannel) {
1262        dmsg(2,("LSCPServer: SetMIDIInputPort(MIDIPort=%d, SamplerChannel=%d)\n",MIDIPort,uiSamplerChannel));
1263        LSCPResultSet result;
1264        try {
1265            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1266            if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1267            pSamplerChannel->SetMidiInputPort(MIDIPort);
1268        }
1269        catch (LinuxSamplerException e) {
1270             result.Error(e);
1271        }
1272        return result.Produce();
1273    }
1274    
1275    String LSCPServer::SetMIDIInputChannel(uint MIDIChannel, uint uiSamplerChannel) {
1276        dmsg(2,("LSCPServer: SetMIDIInputChannel(MIDIChannel=%d, SamplerChannel=%d)\n",MIDIChannel,uiSamplerChannel));
1277        LSCPResultSet result;
1278        try {
1279            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1280            if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1281            pSamplerChannel->SetMidiInputChannel((MidiInputPort::midi_chan_t) MIDIChannel);
1282        }
1283        catch (LinuxSamplerException e) {
1284             result.Error(e);
1285        }
1286        return result.Produce();
1287    }
1288    
1289    String LSCPServer::SetMIDIInputDevice(uint MIDIDeviceId, uint uiSamplerChannel) {
1290        dmsg(2,("LSCPServer: SetMIDIInputDevice(MIDIDeviceId=%d, SamplerChannel=%d)\n",MIDIDeviceId,uiSamplerChannel));
1291        LSCPResultSet result;
1292        try {
1293            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1294            if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1295            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1296            if (!devices.count(MIDIDeviceId)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1297            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1298            pSamplerChannel->SetMidiInputDevice(pDevice);
1299        }
1300        catch (LinuxSamplerException e) {
1301             result.Error(e);
1302        }
1303        return result.Produce();
1304    }
1305    
1306    String LSCPServer::SetMIDIInputType(String MidiInputDriver, uint uiSamplerChannel) {
1307        dmsg(2,("LSCPServer: SetMIDIInputType(String MidiInputDriver=%s, SamplerChannel=%d)\n",MidiInputDriver.c_str(),uiSamplerChannel));
1308        LSCPResultSet result;
1309        try {
1310            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1311            if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1312            // Driver type name aliasing...
1313            if (MidiInputDriver == "Alsa") MidiInputDriver = "ALSA";
1314            // Check if there's one MIDI input device already created
1315            // for the intended MIDI driver type (MidiInputDriver)...
1316            MidiInputDevice *pDevice = NULL;
1317            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1318            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
1319            for (; iter != devices.end(); iter++) {
1320                if ((iter->second)->Driver() == MidiInputDriver) {
1321                    pDevice = iter->second;
1322                    break;
1323                }
1324            }
1325            // If it doesn't exist, create a new one with default parameters...
1326            if (pDevice == NULL) {
1327                std::map<String,String> params;
1328                pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1329                // Make it with at least one initial port.
1330                std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1331                parameters["PORTS"]->SetValue("1");
1332            }
1333            // Must have a device...
1334            if (pDevice == NULL)
1335                throw LinuxSamplerException("Internal error: could not create MIDI input device.");
1336            // Set it as the current channel device...
1337            pSamplerChannel->SetMidiInputDevice(pDevice);
1338        }
1339        catch (LinuxSamplerException e) {
1340             result.Error(e);
1341        }
1342        return result.Produce();
1343  }  }
1344    
1345  /**  /**
1346   * Will be called by the parser to change the MIDI input channel on which the   * Will be called by the parser to change the MIDI input device, port and channel on which
1347   * engine of a particular sampler channel should listen to.   * engine of a particular sampler channel should listen to.
1348   */   */
1349  String LSCPServer::SetMIDIInputChannel(uint MIDIChannel, uint uiSamplerChannel) {  String LSCPServer::SetMIDIInput(uint MIDIDeviceId, uint MIDIPort, uint MIDIChannel, uint uiSamplerChannel) {
1350      dmsg(2,("LSCPServer: SetMIDIInputChannel(MIDIChannel=%d, SamplerChannel=%d)\n", MIDIChannel, uiSamplerChannel));      dmsg(2,("LSCPServer: SetMIDIInput(MIDIDeviceId=%d, MIDIPort=%d, MIDIChannel=%d, SamplerChannel=%d)\n", MIDIDeviceId, MIDIPort, MIDIChannel, uiSamplerChannel));
1351      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
1352        try {
1353            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1354            if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1355            std::map<uint, MidiInputDevice*> devices =  pSampler->GetMidiInputDevices();
1356            if (!devices.count(MIDIDeviceId)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1357            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1358            pSamplerChannel->SetMidiInput(pDevice, MIDIPort, (MidiInputPort::midi_chan_t) MIDIChannel);
1359        }
1360        catch (LinuxSamplerException e) {
1361             result.Error(e);
1362        }
1363        return result.Produce();
1364  }  }
1365    
1366  /**  /**
1367   * Will be called by the parser to change the global volume factor on a   * Will be called by the parser to change the global volume factor on a
1368   * particular sampler channel.   * particular sampler channel.
1369   */   */
1370  String LSCPServer::SetVolume(double Volume, uint uiSamplerChannel) {  String LSCPServer::SetVolume(double dVolume, uint uiSamplerChannel) {
1371      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", Volume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1372      result_t result;      LSCPResultSet result;
1373      try {      try {
1374          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1375          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1376          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1377          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw LinuxSamplerException("No engine type assigned to sampler channel");
1378          pEngine->Volume(Volume);          pEngineChannel->Volume(dVolume);
         result.type = result_type_success;  
1379      }      }
1380      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
1381           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
1382      }      }
1383      return ConvertResult(result);      return result.Produce();
1384  }  }
1385    
1386  /**  /**
# Line 375  String LSCPServer::SetVolume(double Volu Line 1388  String LSCPServer::SetVolume(double Volu
1388   */   */
1389  String LSCPServer::ResetChannel(uint uiSamplerChannel) {  String LSCPServer::ResetChannel(uint uiSamplerChannel) {
1390      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
1391      result_t result;      LSCPResultSet result;
1392      try {      try {
1393          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1394          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));
1395          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1396          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw LinuxSamplerException("No engine type assigned to sampler channel");
1397          pEngine->Reset();          if (!pEngineChannel->GetEngine()) throw LinuxSamplerException("No audio output device connected to sampler channel");
1398          result.type = result_type_success;          pEngineChannel->GetEngine()->Reset();
1399      }      }
1400      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
1401           e.PrintMessage();           result.Error(e);
          result.type    = result_type_error;  
          result.code    = LSCP_ERR_UNKNOWN;  
          result.message = e.Message();  
1402      }      }
1403      return ConvertResult(result);      return result.Produce();
1404    }
1405    
1406    /**
1407     * Will be called by the parser to reset the whole sampler.
1408     */
1409    String LSCPServer::ResetSampler() {
1410        dmsg(2,("LSCPServer: ResetSampler()\n"));
1411        pSampler->Reset();
1412        LSCPResultSet result;
1413        return result.Produce();
1414    }
1415    
1416    /**
1417     * Will be called by the parser to return general informations about this
1418     * sampler.
1419     */
1420    String LSCPServer::GetServerInfo() {
1421        dmsg(2,("LSCPServer: GetServerInfo()\n"));
1422        LSCPResultSet result;
1423        result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");
1424        result.Add("VERSION", VERSION);
1425        result.Add("PROTOCOL_VERSION", "1.0");
1426        return result.Produce();
1427  }  }
1428    
1429  /**  /**
1430   * 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
1431   * server for receiving event messages.   * server for receiving event messages.
1432   */   */
1433  String LSCPServer::SubscribeNotification(uint UDPPort) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
1434      dmsg(2,("LSCPServer: SubscribeNotification(UDPPort=%d)\n", UDPPort));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
1435      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
1436        SubscriptionMutex.Lock();
1437        eventSubscriptions[type].push_back(currentSocket);
1438        SubscriptionMutex.Unlock();
1439        return result.Produce();
1440  }  }
1441    
1442  /**  /**
1443   * 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
1444   * for not receiving further event messages.   * for not receiving further event messages.
1445   */   */
1446  String LSCPServer::UnsubscribeNotification(String SessionID) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
1447      dmsg(2,("LSCPServer: UnsubscribeNotification(SessionID=%s)\n", SessionID.c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
1448      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
1449        SubscriptionMutex.Lock();
1450        eventSubscriptions[type].remove(currentSocket);
1451        SubscriptionMutex.Unlock();
1452        return result.Produce();
1453    }
1454    
1455    static int select_callback(void * lscpResultSet, int argc,
1456                            char **argv, char **azColName)
1457    {
1458        LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;
1459        resultSet->Add(argc, argv);
1460        return 0;
1461    }
1462    
1463    String LSCPServer::QueryDatabase(String query) {
1464        LSCPResultSet result;
1465    #if HAVE_SQLITE3
1466        char* zErrMsg = NULL;
1467        sqlite3 *db;
1468        String selectStr = "SELECT " + query;
1469    
1470        int rc = sqlite3_open("linuxsampler.db", &db);
1471        if (rc == SQLITE_OK)
1472        {
1473                rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);
1474        }
1475        if ( rc != SQLITE_OK )
1476        {
1477                result.Error(String(zErrMsg), rc);
1478        }
1479        sqlite3_close(db);
1480    #else
1481        result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);
1482    #endif
1483        return result.Produce();
1484    }
1485    
1486    /**
1487     * Will be called by the parser to enable or disable echo mode; if echo
1488     * mode is enabled, all commands from the client will (immediately) be
1489     * echoed back to the client.
1490     */
1491    String LSCPServer::SetEcho(yyparse_param_t* pSession, double boolean_value) {
1492        dmsg(2,("LSCPServer: SetEcho(val=%f)\n", boolean_value));
1493        LSCPResultSet result;
1494        try {
1495            if      (boolean_value == 0) pSession->bVerbose = false;
1496            else if (boolean_value == 1) pSession->bVerbose = true;
1497            else throw LinuxSamplerException("Not a boolean value, must either be 0 or 1");
1498        }
1499        catch (LinuxSamplerException e) {
1500             result.Error(e);
1501        }
1502        return result.Produce();
1503  }  }

Legend:
Removed from v.53  
changed lines
  Added in v.620

  ViewVC Help
Powered by ViewVC