/[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 123 by schoenebeck, Mon Jun 14 19:33:16 2004 UTC revision 223 by schoenebeck, Sat Aug 21 11:43:53 2004 UTC
# Line 22  Line 22 
22    
23  #include "lscpserver.h"  #include "lscpserver.h"
24  #include "lscpresultset.h"  #include "lscpresultset.h"
25    #include "lscpevent.h"
26    
27  #include "../engines/gig/Engine.h"  #include "../engines/gig/Engine.h"
28  #include "../audiodriver/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
29    #include "../drivers/midi/MidiInputDeviceFactory.h"
30    
31    /**
32     * Below are a few static members of the LSCPServer class.
33     * The big assumption here is that LSCPServer is going to remain a singleton.
34     * These members are used to support client connections.
35     * Class handles multiple connections at the same time using select() and non-blocking recv()
36     * Commands are processed by a single LSCPServer thread.
37     * Notifications are delivered either by the thread that originated them
38     * or (if the resultset is currently in progress) by the LSCPServer thread
39     * after the resultset was sent out.
40     * This makes sure that resultsets can not be interrupted by notifications.
41     * This also makes sure that the thread sending notification is not blocked
42     * by the LSCPServer thread.
43     */
44    fd_set LSCPServer::fdSet;
45    int LSCPServer::currentSocket = -1;
46    std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
47    std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
48    std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
49    std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
50    Mutex LSCPServer::NotifyMutex = Mutex();
51    Mutex LSCPServer::NotifyBufferMutex = Mutex();
52    Mutex LSCPServer::SubscriptionMutex = Mutex();
53    
54  LSCPServer::LSCPServer(Sampler* pSampler) : Thread(false, 0, -4) {  LSCPServer::LSCPServer(Sampler* pSampler) : Thread(false, 0, -4) {
55      this->pSampler = pSampler;      this->pSampler = pSampler;
56        LSCPEvent::RegisterEvent(LSCPEvent::event_channels, "CHANNELS");
57        LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");
58        LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
59        LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
60        LSCPEvent::RegisterEvent(LSCPEvent::event_info, "INFO");
61        LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
62    }
63    
64    /**
65     * Blocks the calling thread until the LSCP Server is initialized and
66     * accepting socket connections, if the server is already initialized then
67     * this method will return immediately.
68     * @param TimeoutSeconds     - optional: max. wait time in seconds
69     *                             (default: 0s)
70     * @param TimeoutNanoSeconds - optional: max wait time in nano seconds
71     *                             (default: 0ns)
72     * @returns  0 on success, a value less than 0 if timeout exceeded
73     */
74    int LSCPServer::WaitUntilInitialized(long TimeoutSeconds, long TimeoutNanoSeconds) {
75        return Initialized.WaitAndUnlockIf(false, TimeoutSeconds, TimeoutNanoSeconds);
76  }  }
77    
78  int LSCPServer::Main() {  int LSCPServer::Main() {
79      hSocket = socket(AF_INET, SOCK_STREAM, 0);      int hSocket = socket(AF_INET, SOCK_STREAM, 0);
80      if (hSocket < 0) {      if (hSocket < 0) {
81          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
82          //return -1;          //return -1;
# Line 50  int LSCPServer::Main() { Line 95  int LSCPServer::Main() {
95      }      }
96    
97      listen(hSocket, 1);      listen(hSocket, 1);
98      dmsg(1,("LSCPServer: Server running.\n")); // server running      Initialized.Set(true);
99    
100      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
101      sockaddr_in client;      sockaddr_in client;
102      int length = sizeof(client);      int length = sizeof(client);
103        FD_ZERO(&fdSet);
104        FD_SET(hSocket, &fdSet);
105        int maxSessions = hSocket;
106    
107      while (true) {      while (true) {
108          hSession = accept(hSocket, (sockaddr*) &client, (socklen_t*) &length);          fd_set selectSet = fdSet;
109          if (hSession < 0) {          int retval = select(maxSessions+1, &selectSet, NULL, NULL, NULL);
110              std::cerr << "LSCPServer: Client connection failed." << std::endl;          if (retval == 0)
111              close(hSocket);                  continue; //Nothing try again
112              //return -1;          if (retval == -1) {
113              exit(EXIT_FAILURE);                  std::cerr << "LSCPServer: Socket select error." << std::endl;
114          }                  close(hSocket);
115                    exit(EXIT_FAILURE);
116          dmsg(1,("LSCPServer: Client connection established.\n"));          }
117          //send(hSession, "Welcome!\r\n", 10, 0);  
118            //Accept new connections now (if any)
119          // Parser invocation          if (FD_ISSET(hSocket, &selectSet)) {
120          yyparse_param_t yyparse_param;                  int socket = accept(hSocket, (sockaddr*) &client, (socklen_t*) &length);
121          yyparse_param.pServer = this;                  if (socket < 0) {
122          yylex_init(&yyparse_param.pScanner);                          std::cerr << "LSCPServer: Client connection failed." << std::endl;
123          while (yyparse(&yyparse_param) == LSCP_SYNTAX_ERROR); // recall parser in case of syntax error                          exit(EXIT_FAILURE);
124          yylex_destroy(yyparse_param.pScanner);                  }
125    
126                    if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
127                            std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
128                            exit(EXIT_FAILURE);
129                    }
130    
131                    // Parser initialization
132                    yyparse_param_t yyparse_param;
133                    yyparse_param.pServer  = this;
134                    yyparse_param.hSession = socket;
135    
136                    Sessions.push_back(yyparse_param);
137                    FD_SET(socket, &fdSet);
138                    if (socket > maxSessions)
139                            maxSessions = socket;
140                    dmsg(1,("LSCPServer: Client connection established on socket:%d.\n", socket));
141                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection established on socket", socket));
142                    continue; //Maybe this was the only selected socket, better select again
143            }
144    
145            //Something was selected and it was not the hSocket, so it must be some command(s) coming.
146            for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {
147                    if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?
148                            if (GetLSCPCommand(iter)) {     //Have we read the entire command?
149                                    dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));
150                                    int dummy; // just a temporary hack to fulfill the restart() function prototype
151                                    restart(NULL, dummy); // restart the 'scanner'
152                                    currentSocket = (*iter).hSession;  //a hack
153                                    if ((*iter).bVerbose) { // if echo mode enabled
154                                        AnswerClient(bufferedCommands[currentSocket]);
155                                    }
156                                    int result = yyparse(&(*iter));
157                                    currentSocket = -1;     //continuation of a hack
158                                    dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
159                                    if (result == LSCP_QUIT) { //Was it a quit command by any chance?
160                                            CloseConnection(iter);
161                                    }
162                            }
163                            //socket may have been closed, iter may be invalid, get out of the loop for now.
164                            //we'll be back if there is data.
165                            break;
166                    }
167            }
168    
169          close(hSession);          //Now let's deliver late notifies (if any)
170          dmsg(1,("LSCPServer: Client connection terminated.\n"));          NotifyBufferMutex.Lock();
171            for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
172                    send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
173                    bufferedNotifies.erase(iterNotify);
174            }
175            NotifyBufferMutex.Unlock();
176      }      }
177  }  }
178    
179    void LSCPServer::CloseConnection( std::vector<yyparse_param_t>::iterator iter ) {
180            int socket = (*iter).hSession;
181            dmsg(1,("LSCPServer: Client connection terminated on socket:%d.\n",socket));
182            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
183            Sessions.erase(iter);
184            FD_CLR(socket,  &fdSet);
185            SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)
186            for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {
187                    iter->second.remove(socket);
188            }
189            SubscriptionMutex.Unlock();
190            NotifyMutex.Lock();
191            bufferedCommands.erase(socket);
192            bufferedNotifies.erase(socket);
193            close(socket);
194            NotifyMutex.Unlock();
195    }
196    
197    void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
198            SubscriptionMutex.Lock();
199            if (eventSubscriptions.count(event.GetType()) == 0) {
200                    SubscriptionMutex.Unlock();     //Nobody is subscribed to this event
201                    return;
202            }
203            std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
204            std::list<int>::iterator end = eventSubscriptions[event.GetType()].end();
205            String notify = event.Produce();
206    
207            while (true) {
208                    if (NotifyMutex.Trylock()) {
209                            for(;iter != end; iter++)
210                                    send(*iter, notify.c_str(), notify.size(), 0);
211                            NotifyMutex.Unlock();
212                            break;
213                    } else {
214                            if (NotifyBufferMutex.Trylock()) {
215                                    for(;iter != end; iter++)
216                                            bufferedNotifies[*iter] += notify;
217                                    NotifyBufferMutex.Unlock();
218                                    break;
219                            }
220                    }
221            }
222            SubscriptionMutex.Unlock();
223    }
224    
225    extern int GetLSCPCommand( void *buf, int max_size ) {
226            String command = LSCPServer::bufferedCommands[LSCPServer::currentSocket];
227            if (command.size() == 0) {              //Parser wants input but we have nothing.
228                    strcpy((char*) buf, "\n");      //So give it an empty command
229                    return 1;                       //to keep it happy.
230            }
231    
232            if (max_size < command.size()) {
233                    std::cerr << "getLSCPCommand: Flex buffer too small, ignoring the command." << std::endl;
234                    return 0;       //This will never happen
235            }
236    
237            strcpy((char*) buf, command.c_str());
238            LSCPServer::bufferedCommands.erase(LSCPServer::currentSocket);
239            return command.size();
240    }
241    
242    /**
243     * Will be called to try to read the command from the socket
244     * If command is read, it will return true. Otherwise false is returned.
245     * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.
246     */
247    bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {
248            int socket = (*iter).hSession;
249            char c;
250            int i = 0;
251            while (true) {
252                    int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
253                    if (result == 0) { //socket was selected, so 0 here means client has closed the connection
254                            CloseConnection(iter);
255                            break;
256                    }
257                    if (result == 1) {
258                            if (c == '\r')
259                                    continue; //Ignore CR
260                            if (c == '\n') {
261                                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
262                                    bufferedCommands[socket] += "\n";
263                                    return true; //Complete command was read
264                            }
265                            bufferedCommands[socket] += c;
266                    }
267                    if (result == -1) {
268                            if (errno == EAGAIN) //Would block, try again later.
269                                    return false;
270                            switch(errno) {
271                                    case EBADF:
272                                            dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
273                                            break;
274                                    case ECONNREFUSED:
275                                            dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
276                                            break;
277                                    case ENOTCONN:
278                                            dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));
279                                            break;
280                                    case ENOTSOCK:
281                                            dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
282                                            break;
283                                    case EAGAIN:
284                                            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"));
285                                            break;
286                                    case EINTR:
287                                            dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
288                                            break;
289                                    case EFAULT:
290                                            dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
291                                            break;
292                                    case EINVAL:
293                                            dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
294                                            break;
295                                    case ENOMEM:
296                                            dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
297                                            break;
298                                    default:
299                                            dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
300                                            break;
301                            }
302                            CloseConnection(iter);
303                            break;
304                    }
305            }
306            return false;
307    }
308    
309  /**  /**
310   * Will be called by the parser whenever it wants to send an answer to the   * Will be called by the parser whenever it wants to send an answer to the
311   * client / frontend.   * client / frontend.
# Line 87  int LSCPServer::Main() { Line 314  int LSCPServer::Main() {
314   */   */
315  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
316      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));
317      send(hSession, ReturnMessage.c_str(), ReturnMessage.size(), 0);      if (currentSocket != -1) {
318                NotifyMutex.Lock();
319                send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
320                NotifyMutex.Unlock();
321        }
322    }
323    
324    /**
325     * Find a created audio output device index.
326     */
327    int LSCPServer::GetAudioOutputDeviceIndex ( AudioOutputDevice *pDevice )
328    {
329        // Search for the created device to get its index
330        std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
331        std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
332        for (; iter != devices.end(); iter++) {
333            if (iter->second == pDevice)
334                return iter->first;
335        }
336        // Not found.
337        return -1;
338    }
339    
340    /**
341     * Find a created midi input device index.
342     */
343    int LSCPServer::GetMidiInputDeviceIndex ( MidiInputDevice *pDevice )
344    {
345        // Search for the created device to get its index
346        std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
347        std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
348        for (; iter != devices.end(); iter++) {
349            if (iter->second == pDevice)
350                return iter->first;
351        }
352        // Not found.
353        return -1;
354  }  }
355    
356  String LSCPServer::CreateAudioOutputDevice(String Driver, std::map<String,String> Parameters) {  String LSCPServer::CreateAudioOutputDevice(String Driver, std::map<String,String> Parameters) {
# Line 95  String LSCPServer::CreateAudioOutputDevi Line 358  String LSCPServer::CreateAudioOutputDevi
358      LSCPResultSet result;      LSCPResultSet result;
359      try {      try {
360          AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);          AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);
         std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();  
361          // search for the created device to get its index          // search for the created device to get its index
362          int index = -1;          int index = GetAudioOutputDeviceIndex(pDevice);
         std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();  
         for (; iter != devices.end(); iter++) {  
             if (iter->second == pDevice) {  
                 index = iter->first;  
                 break;  
             }  
         }  
363          if (index == -1) throw LinuxSamplerException("Internal error: could not find created audio output device.");          if (index == -1) throw LinuxSamplerException("Internal error: could not find created audio output device.");
364          result = index; // success          result = index; // success
365      }      }
# Line 114  String LSCPServer::CreateAudioOutputDevi Line 369  String LSCPServer::CreateAudioOutputDevi
369      return result.Produce();      return result.Produce();
370  }  }
371    
372    String LSCPServer::CreateMidiInputDevice(String Driver, std::map<String,String> Parameters) {
373        dmsg(2,("LSCPServer: CreateMidiInputDevice(Driver=%s)\n", Driver.c_str()));
374        LSCPResultSet result;
375        try {
376            MidiInputDevice* pDevice = pSampler->CreateMidiInputDevice(Driver, Parameters);
377            // search for the created device to get its index
378            int index = GetMidiInputDeviceIndex(pDevice);
379            if (index == -1) throw LinuxSamplerException("Internal error: could not find created midi input device.");
380            result = index; // success
381        }
382        catch (LinuxSamplerException e) {
383            result.Error(e);
384        }
385        return result.Produce();
386    }
387    
388  String LSCPServer::DestroyAudioOutputDevice(uint DeviceIndex) {  String LSCPServer::DestroyAudioOutputDevice(uint DeviceIndex) {
389      dmsg(2,("LSCPServer: DestroyAudioOutputDevice(DeviceIndex=%d)\n", DeviceIndex));      dmsg(2,("LSCPServer: DestroyAudioOutputDevice(DeviceIndex=%d)\n", DeviceIndex));
390      LSCPResultSet result;      LSCPResultSet result;
391      try {      try {
392          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
393          if (!devices[DeviceIndex]) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
394          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
395          pSampler->DestroyAudioOutputDevice(pDevice);          pSampler->DestroyAudioOutputDevice(pDevice);
396      }      }
# Line 129  String LSCPServer::DestroyAudioOutputDev Line 400  String LSCPServer::DestroyAudioOutputDev
400      return result.Produce();      return result.Produce();
401  }  }
402    
403    String LSCPServer::DestroyMidiInputDevice(uint DeviceIndex) {
404        dmsg(2,("LSCPServer: DestroyMidiInputDevice(DeviceIndex=%d)\n", DeviceIndex));
405        LSCPResultSet result;
406        try {
407            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
408            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
409            MidiInputDevice* pDevice = devices[DeviceIndex];
410            pSampler->DestroyMidiInputDevice(pDevice);
411        }
412        catch (LinuxSamplerException e) {
413            result.Error(e);
414        }
415        return result.Produce();
416    }
417    
418  /**  /**
419   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
420   */   */
421  String LSCPServer::LoadInstrument(String Filename, uint uiInstrument, uint uiSamplerChannel) {  String LSCPServer::LoadInstrument(String Filename, uint uiInstrument, uint uiSamplerChannel, bool bBackground) {
422      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));
423      LSCPResultSet result;      LSCPResultSet result;
424      try {      try {
# Line 140  String LSCPServer::LoadInstrument(String Line 426  String LSCPServer::LoadInstrument(String
426          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");
427          Engine* pEngine = pSamplerChannel->GetEngine();          Engine* pEngine = pSamplerChannel->GetEngine();
428          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");
429          pEngine->LoadInstrument(Filename.c_str(), uiInstrument);          if (!pSamplerChannel->GetAudioOutputDevice())
430                throw LinuxSamplerException("No audio output device on channel");
431            if (bBackground) {
432                LSCPLoadInstrument *pLoadInstrument = new LSCPLoadInstrument(pEngine, Filename.c_str(), uiInstrument);
433                pLoadInstrument->StartThread();
434            }
435            else pEngine->LoadInstrument(Filename.c_str(), uiInstrument);
436      }      }
437      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
438           result.Error(e);           result.Error(e);
# Line 179  String LSCPServer::GetChannels() { Line 471  String LSCPServer::GetChannels() {
471  }  }
472    
473  /**  /**
474     * Will be called by the parser to get the list of sampler channels.
475     */
476    String LSCPServer::ListChannels() {
477        dmsg(2,("LSCPServer: ListChannels()\n"));
478        String list;
479        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
480        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
481        for (; iter != channels.end(); iter++) {
482            if (list != "") list += ",";
483            list += ToString(iter->first);
484        }
485        LSCPResultSet result;
486        result.Add(list);
487        return result.Produce();
488    }
489    
490    /**
491   * Will be called by the parser to add a sampler channel.   * Will be called by the parser to add a sampler channel.
492   */   */
493  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
# Line 244  String LSCPServer::GetChannelInfo(uint u Line 553  String LSCPServer::GetChannelInfo(uint u
553          String EngineName = "NONE";          String EngineName = "NONE";
554          float Volume = 0;          float Volume = 0;
555          String InstrumentFileName = "NONE";          String InstrumentFileName = "NONE";
556          int InstrumentIndex = 0;          int InstrumentIndex = -1;
557            int InstrumentStatus = -1;
558    
559          if (pEngine) {          if (pEngine) {
560              EngineName =  pEngine->EngineName();              EngineName =  pEngine->EngineName();
561              Volume = pEngine->Volume();              Volume = pEngine->Volume();
562              int iIdx = pEngine->InstrumentIndex();              InstrumentStatus = pEngine->InstrumentStatus();
563              if (iIdx != -1) {              InstrumentIndex = pEngine->InstrumentIndex();
564                if (InstrumentIndex != -1)
565                  InstrumentFileName = pEngine->InstrumentFileName();                  InstrumentFileName = pEngine->InstrumentFileName();
                 InstrumentIndex = iIdx;  
             }  
566          }          }
567    
568          result.Add("ENGINE_NAME", EngineName);          result.Add("ENGINE_NAME", EngineName);
569          result.Add("VOLUME", Volume);          result.Add("VOLUME", Volume);
570    
571          //Some hardcoded stuff for now to make GUI look good          //Some not-so-hardcoded stuff to make GUI look good
572          result.Add("AUDIO_OUTPUT_DEVICE", "0");          result.Add("AUDIO_OUTPUT_DEVICE", GetAudioOutputDeviceIndex(pSamplerChannel->GetAudioOutputDevice()));
573          result.Add("AUDIO_OUTPUT_CHANNELS", "2");          result.Add("AUDIO_OUTPUT_CHANNELS", "2");
574          result.Add("AUDIO_OUTPUT_ROUTING", "0,1");          result.Add("AUDIO_OUTPUT_ROUTING", "0,1");
575    
576            result.Add("MIDI_INPUT_DEVICE", GetMidiInputDeviceIndex(pSamplerChannel->GetMidiInputDevice()));
577            result.Add("MIDI_INPUT_PORT", pSamplerChannel->GetMidiInputPort());
578            result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
579    
580          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
581          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
582            result.Add("INSTRUMENT_STATUS", InstrumentStatus);
         //Some more hardcoded stuff for now to make GUI look good  
         result.Add("MIDI_INPUT_DEVICE", "0");  
         result.Add("MIDI_INPUT_PORT", "0");  
         result.Add("MIDI_INPUT_CHANNEL", "1");  
583      }      }
584      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
585           result.Error(e);           result.Error(e);
# Line 330  String LSCPServer::GetBufferFill(fill_re Line 639  String LSCPServer::GetBufferFill(fill_re
639          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");
640          Engine* pEngine = pSamplerChannel->GetEngine();          Engine* pEngine = pSamplerChannel->GetEngine();
641          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");
642          if (!pEngine->DiskStreamSupported()) return "NA\r\n"; //FIXME: Update resultset class to support "NA"          if (!pEngine->DiskStreamSupported())
643          switch (ResponseType) {              result.Add("NA");
644              case fill_response_bytes:          else {
645                  result.Add(pEngine->DiskStreamBufferFillBytes());              switch (ResponseType) {
646                  break;                  case fill_response_bytes:
647              case fill_response_percentage:                      result.Add(pEngine->DiskStreamBufferFillBytes());
648                  result.Add(pEngine->DiskStreamBufferFillPercentage());                      break;
649                  break;                  case fill_response_percentage:
650              default:                      result.Add(pEngine->DiskStreamBufferFillPercentage());
651                  throw LinuxSamplerException("Unknown fill response type");                      break;
652          }                  default:
653                        throw LinuxSamplerException("Unknown fill response type");
654                }
655            }
656      }      }
657      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
658           result.Error(e);           result.Error(e);
# Line 361  String LSCPServer::GetAvailableAudioOutp Line 673  String LSCPServer::GetAvailableAudioOutp
673      return result.Produce();      return result.Produce();
674  }  }
675    
676    String LSCPServer::GetAvailableMidiInputDrivers() {
677        dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));
678        LSCPResultSet result;
679        try {
680            String s = MidiInputDeviceFactory::AvailableDriversAsString();
681            result.Add(s);
682        }
683        catch (LinuxSamplerException e) {
684            result.Error(e);
685        }
686        return result.Produce();
687    }
688    
689    String LSCPServer::GetMidiInputDriverInfo(String Driver) {
690        dmsg(2,("LSCPServer: GetMidiInputDriverInfo(Driver=%s)\n",Driver.c_str()));
691        LSCPResultSet result;
692        try {
693            result.Add("DESCRIPTION", MidiInputDeviceFactory::GetDriverDescription(Driver));
694            result.Add("VERSION",     MidiInputDeviceFactory::GetDriverVersion(Driver));
695    
696            std::map<String,DeviceCreationParameter*> parameters = MidiInputDeviceFactory::GetAvailableDriverParameters(Driver);
697            if (parameters.size()) { // if there are parameters defined for this driver
698                String s;
699                std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
700                for (;iter != parameters.end(); iter++) {
701                    if (s != "") s += ",";
702                    s += iter->first;
703                }
704                result.Add("PARAMETERS", s);
705            }
706        }
707        catch (LinuxSamplerException e) {
708            result.Error(e);
709        }
710        return result.Produce();
711    }
712    
713  String LSCPServer::GetAudioOutputDriverInfo(String Driver) {  String LSCPServer::GetAudioOutputDriverInfo(String Driver) {
714      dmsg(2,("LSCPServer: GetAudioOutputDriverInfo(Driver=%s)\n",Driver.c_str()));      dmsg(2,("LSCPServer: GetAudioOutputDriverInfo(Driver=%s)\n",Driver.c_str()));
715      LSCPResultSet result;      LSCPResultSet result;
# Line 385  String LSCPServer::GetAudioOutputDriverI Line 734  String LSCPServer::GetAudioOutputDriverI
734      return result.Produce();      return result.Produce();
735  }  }
736    
737    String LSCPServer::GetMidiInputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
738        dmsg(2,("LSCPServer: GetMidiInputDriverParameterInfo(Driver=%s,Parameter=%s)\n",Driver.c_str(),Parameter.c_str()));
739        LSCPResultSet result;
740        try {
741            DeviceCreationParameter* pParameter = MidiInputDeviceFactory::GetDriverParameter(Driver, Parameter);
742            result.Add("TYPE",         pParameter->Type());
743            result.Add("DESCRIPTION",  pParameter->Description());
744            result.Add("MANDATORY",    pParameter->Mandatory());
745            result.Add("FIX",          pParameter->Fix());
746            result.Add("MULTIPLICITY", pParameter->Multiplicity());
747            if (pParameter->Depends())       result.Add("DEPENDS",       *pParameter->Depends());
748            if (pParameter->Default())       result.Add("DEFAULT",       *pParameter->Default());
749            if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
750            if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
751            if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
752        }
753        catch (LinuxSamplerException e) {
754            result.Error(e);
755        }
756        return result.Produce();
757    }
758    
759  String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {  String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
760      dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s)\n",Driver.c_str(),Parameter.c_str()));      dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s)\n",Driver.c_str(),Parameter.c_str()));
761      LSCPResultSet result;      LSCPResultSet result;
# Line 395  String LSCPServer::GetAudioOutputDriverP Line 766  String LSCPServer::GetAudioOutputDriverP
766          result.Add("MANDATORY",    pParameter->Mandatory());          result.Add("MANDATORY",    pParameter->Mandatory());
767          result.Add("FIX",          pParameter->Fix());          result.Add("FIX",          pParameter->Fix());
768          result.Add("MULTIPLICITY", pParameter->Multiplicity());          result.Add("MULTIPLICITY", pParameter->Multiplicity());
769          if (pParameter->Depends())       result.Add("DEPENDS",       pParameter->Depends());          if (pParameter->Depends())       result.Add("DEPENDS",       *pParameter->Depends());
770          if (pParameter->Default())       result.Add("DEFAULT",       pParameter->Default());          if (pParameter->Default())       result.Add("DEFAULT",       *pParameter->Default());
771          if (pParameter->RangeMin())      result.Add("RANGE_MIN",     pParameter->RangeMin());          if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
772          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     pParameter->RangeMax());          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
773          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", pParameter->Possibilities());          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
774      }      }
775      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
776          result.Error(e);          result.Error(e);
# Line 412  String LSCPServer::GetAudioOutputDeviceC Line 783  String LSCPServer::GetAudioOutputDeviceC
783      LSCPResultSet result;      LSCPResultSet result;
784      try {      try {
785          uint count = pSampler->AudioOutputDevices();          uint count = pSampler->AudioOutputDevices();
786          result = count; // success          result.Add(count); // success
787        }
788        catch (LinuxSamplerException e) {
789            result.Error(e);
790        }
791        return result.Produce();
792    }
793    
794    String LSCPServer::GetMidiInputDeviceCount() {
795        dmsg(2,("LSCPServer: GetMidiInputDeviceCount()\n"));
796        LSCPResultSet result;
797        try {
798            uint count = pSampler->MidiInputDevices();
799            result.Add(count); // success
800      }      }
801      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
802          result.Error(e);          result.Error(e);
# Line 439  String LSCPServer::GetAudioOutputDevices Line 823  String LSCPServer::GetAudioOutputDevices
823      return result.Produce();      return result.Produce();
824  }  }
825    
826    String LSCPServer::GetMidiInputDevices() {
827        dmsg(2,("LSCPServer: GetMidiInputDevices()\n"));
828        LSCPResultSet result;
829        try {
830            String s;
831            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
832            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
833            for (; iter != devices.end(); iter++) {
834                if (s != "") s += ",";
835                s += ToString(iter->first);
836            }
837            result.Add(s);
838        }
839        catch (LinuxSamplerException e) {
840            result.Error(e);
841        }
842        return result.Produce();
843    }
844    
845  String LSCPServer::GetAudioOutputDeviceInfo(uint DeviceIndex) {  String LSCPServer::GetAudioOutputDeviceInfo(uint DeviceIndex) {
846      dmsg(2,("LSCPServer: GetAudioOutputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));      dmsg(2,("LSCPServer: GetAudioOutputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));
847      LSCPResultSet result;      LSCPResultSet result;
848      try {      try {
849          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
850          if (!devices[DeviceIndex]) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
851          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
852            result.Add("DRIVER", pDevice->Driver());
853          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
854          std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();          std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
855          for (; iter != parameters.end(); iter++) {          for (; iter != parameters.end(); iter++) {
# Line 458  String LSCPServer::GetAudioOutputDeviceI Line 862  String LSCPServer::GetAudioOutputDeviceI
862      return result.Produce();      return result.Produce();
863  }  }
864    
865    String LSCPServer::GetMidiInputDeviceInfo(uint DeviceIndex) {
866        dmsg(2,("LSCPServer: GetMidiInputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));
867        LSCPResultSet result;
868        try {
869            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
870            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
871            MidiInputDevice* pDevice = devices[DeviceIndex];
872            result.Add("DRIVER", pDevice->Driver());
873            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
874            std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
875            for (; iter != parameters.end(); iter++) {
876                result.Add(iter->first, iter->second->Value());
877            }
878        }
879        catch (LinuxSamplerException e) {
880            result.Error(e);
881        }
882        return result.Produce();
883    }
884    String LSCPServer::GetMidiInputPortInfo(uint DeviceIndex, uint PortIndex) {
885        dmsg(2,("LSCPServer: GetMidiInputPortInfo(DeviceIndex=%d, PortIndex=%d)\n",DeviceIndex, PortIndex));
886        LSCPResultSet result;
887        try {
888            // get MIDI input device
889            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
890            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
891            MidiInputDevice* pDevice = devices[DeviceIndex];
892    
893            // get MIDI port
894            MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
895            if (!pMidiInputPort) throw LinuxSamplerException("There is no MIDI input port with index " + ToString(PortIndex) + ".");
896    
897            // return the values of all MIDI port parameters
898            std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
899            std::map<String,DeviceRuntimeParameter*>::iterator iter = parameters.begin();
900            for (; iter != parameters.end(); iter++) {
901                result.Add(iter->first, iter->second->Value());
902            }
903        }
904        catch (LinuxSamplerException e) {
905            result.Error(e);
906        }
907        return result.Produce();
908    }
909    
910  String LSCPServer::GetAudioOutputChannelInfo(uint DeviceId, uint ChannelId) {  String LSCPServer::GetAudioOutputChannelInfo(uint DeviceId, uint ChannelId) {
911      dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%d,ChannelId)\n",DeviceId,ChannelId));      dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%d,ChannelId)\n",DeviceId,ChannelId));
912      LSCPResultSet result;      LSCPResultSet result;
913      try {      try {
914          // get audio output device          // get audio output device
915          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
916          if (!devices[DeviceId]) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");          if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");
917          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
918    
919          // get audio channel          // get audio channel
# Line 484  String LSCPServer::GetAudioOutputChannel Line 933  String LSCPServer::GetAudioOutputChannel
933      return result.Produce();      return result.Produce();
934  }  }
935    
936    String LSCPServer::GetMidiInputPortParameterInfo(uint DeviceId, uint PortId, String ParameterName) {
937        dmsg(2,("LSCPServer: GetMidiInputPortParameterInfo(DeviceId=%d,PortId=%d,ParameterName=%s)\n",DeviceId,PortId,ParameterName.c_str()));
938        LSCPResultSet result;
939        try {
940            // get MIDI input device
941            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
942            if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no midi input device with index " + ToString(DeviceId) + ".");
943            MidiInputDevice* pDevice = devices[DeviceId];
944    
945            // get midi port
946            MidiInputPort* pPort = pDevice->GetPort(PortId);
947            if (!pPort) throw LinuxSamplerException("Midi input device does not have port " + ToString(PortId) + ".");
948    
949            // get desired port parameter
950            std::map<String,DeviceRuntimeParameter*> parameters = pPort->PortParameters();
951            if (!parameters.count(ParameterName)) throw LinuxSamplerException("Midi port does not provide a parameter '" + ParameterName + "'.");
952            DeviceRuntimeParameter* pParameter = parameters[ParameterName];
953    
954            // return all fields of this audio channel parameter
955            result.Add("TYPE",         pParameter->Type());
956            result.Add("DESCRIPTION",  pParameter->Description());
957            result.Add("FIX",          pParameter->Fix());
958            result.Add("MULTIPLICITY", pParameter->Multiplicity());
959            if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
960            if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
961            if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
962        }
963        catch (LinuxSamplerException e) {
964            result.Error(e);
965        }
966        return result.Produce();
967    }
968    
969  String LSCPServer::GetAudioOutputChannelParameterInfo(uint DeviceId, uint ChannelId, String ParameterName) {  String LSCPServer::GetAudioOutputChannelParameterInfo(uint DeviceId, uint ChannelId, String ParameterName) {
970      dmsg(2,("LSCPServer: GetAudioOutputChannelParameterInfo(DeviceId=%d,ChannelId=%d,ParameterName=%s)\n",DeviceId,ChannelId,ParameterName.c_str()));      dmsg(2,("LSCPServer: GetAudioOutputChannelParameterInfo(DeviceId=%d,ChannelId=%d,ParameterName=%s)\n",DeviceId,ChannelId,ParameterName.c_str()));
971      LSCPResultSet result;      LSCPResultSet result;
972      try {      try {
973          // get audio output device          // get audio output device
974          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
975          if (!devices[DeviceId]) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");          if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");
976          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
977    
978          // get audio channel          // get audio channel
# Line 499  String LSCPServer::GetAudioOutputChannel Line 981  String LSCPServer::GetAudioOutputChannel
981    
982          // get desired audio channel parameter          // get desired audio channel parameter
983          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
984          if (!parameters[ParameterName]) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParameterName + "'.");          if (!parameters.count(ParameterName)) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParameterName + "'.");
985          DeviceRuntimeParameter* pParameter = parameters[ParameterName];          DeviceRuntimeParameter* pParameter = parameters[ParameterName];
986    
987          // return all fields of this audio channel parameter          // return all fields of this audio channel parameter
# Line 507  String LSCPServer::GetAudioOutputChannel Line 989  String LSCPServer::GetAudioOutputChannel
989          result.Add("DESCRIPTION",  pParameter->Description());          result.Add("DESCRIPTION",  pParameter->Description());
990          result.Add("FIX",          pParameter->Fix());          result.Add("FIX",          pParameter->Fix());
991          result.Add("MULTIPLICITY", pParameter->Multiplicity());          result.Add("MULTIPLICITY", pParameter->Multiplicity());
992          if (pParameter->RangeMin())      result.Add("RANGE_MIN",     pParameter->RangeMin());          if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
993          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     pParameter->RangeMax());          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
994          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", pParameter->Possibilities());          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
995      }      }
996      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
997          result.Error(e);          result.Error(e);
# Line 523  String LSCPServer::SetAudioOutputChannel Line 1005  String LSCPServer::SetAudioOutputChannel
1005      try {      try {
1006          // get audio output device          // get audio output device
1007          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1008          if (!devices[DeviceId]) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");          if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");
1009          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
1010    
1011          // get audio channel          // get audio channel
# Line 532  String LSCPServer::SetAudioOutputChannel Line 1014  String LSCPServer::SetAudioOutputChannel
1014    
1015          // get desired audio channel parameter          // get desired audio channel parameter
1016          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1017          if (!parameters[ParamKey]) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParamKey + "'.");          if (!parameters.count(ParamKey)) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParamKey + "'.");
1018          DeviceRuntimeParameter* pParameter = parameters[ParamKey];          DeviceRuntimeParameter* pParameter = parameters[ParamKey];
1019    
1020          // set new channel parameter value          // set new channel parameter value
# Line 549  String LSCPServer::SetAudioOutputDeviceP Line 1031  String LSCPServer::SetAudioOutputDeviceP
1031      LSCPResultSet result;      LSCPResultSet result;
1032      try {      try {
1033          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1034          if (!devices[DeviceIndex]) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");
1035          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
1036          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1037          if (!parameters[ParamKey]) throw LinuxSamplerException("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");          if (!parameters.count(ParamKey)) throw LinuxSamplerException("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1038            parameters[ParamKey]->SetValue(ParamVal);
1039        }
1040        catch (LinuxSamplerException e) {
1041            result.Error(e);
1042        }
1043        return result.Produce();
1044    }
1045    
1046    String LSCPServer::SetMidiInputDeviceParameter(uint DeviceIndex, String ParamKey, String ParamVal) {
1047        dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1048        LSCPResultSet result;
1049        try {
1050            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1051            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1052            MidiInputDevice* pDevice = devices[DeviceIndex];
1053            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1054            if (!parameters.count(ParamKey)) throw LinuxSamplerException("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1055            parameters[ParamKey]->SetValue(ParamVal);
1056        }
1057        catch (LinuxSamplerException e) {
1058            result.Error(e);
1059        }
1060        return result.Produce();
1061    }
1062    
1063    String LSCPServer::SetMidiInputPortParameter(uint DeviceIndex, uint PortIndex, String ParamKey, String ParamVal) {
1064        dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1065        LSCPResultSet result;
1066        try {
1067            // get MIDI input device
1068            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1069            if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1070            MidiInputDevice* pDevice = devices[DeviceIndex];
1071    
1072            // get MIDI port
1073            MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1074            if (!pMidiInputPort) throw LinuxSamplerException("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1075    
1076            // set port parameter value
1077            std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1078            if (!parameters.count(ParamKey)) throw LinuxSamplerException("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");
1079          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1080      }      }
1081      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
# Line 570  String LSCPServer::SetAudioOutputChannel Line 1093  String LSCPServer::SetAudioOutputChannel
1093      return "ERR:0:Not implemented yet.\r\n"; //FIXME: Add support for this in resultset class?      return "ERR:0:Not implemented yet.\r\n"; //FIXME: Add support for this in resultset class?
1094  }  }
1095    
1096  String LSCPServer::SetMIDIInputType(String MidiInputDriver, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1097      dmsg(2,("LSCPServer: SetMIDIInputType(String MidiInputDriver=%s, SamplerChannel=%d)\n",MidiInputDriver.c_str(),uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1098      LSCPResultSet result;      LSCPResultSet result;
1099      try {      try {
1100          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1101          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid channel number " + ToString(uiSamplerChannel));
1102          // FIXME: workaround until MIDI driver configuration is implemented (using a Factory class for the MIDI input drivers then, like its already done for audio output drivers)          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1103          if (MidiInputDriver != "ALSA") throw LinuxSamplerException("Unknown MIDI input driver '" + MidiInputDriver + "'.");          if (!devices.count(AudioDeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(AudioDeviceId));
1104          MidiInputDevice::type_t MidiInputType = MidiInputDevice::type_alsa;          AudioOutputDevice* pDevice = devices[AudioDeviceId];
1105          pSamplerChannel->SetMidiInputDevice(MidiInputType);          pSamplerChannel->SetAudioOutputDevice(pDevice);
1106      }      }
1107      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
1108           result.Error(e);           result.Error(e);
# Line 587  String LSCPServer::SetMIDIInputType(Stri Line 1110  String LSCPServer::SetMIDIInputType(Stri
1110      return result.Produce();      return result.Produce();
1111  }  }
1112    
1113  /**  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1114   * 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));
  * engine of a particular sampler channel should listen to.  
  */  
 String LSCPServer::SetMIDIInputPort(String MIDIInputPort, uint uiSamplerChannel) {  
     dmsg(2,("LSCPServer: SetMIDIInputPort(MIDIInputPort=%s, Samplerchannel=%d)\n", MIDIInputPort.c_str(), uiSamplerChannel));  
1115      LSCPResultSet result;      LSCPResultSet result;
1116      try {      try {
1117          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1118          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid channel number " + ToString(uiSamplerChannel));
1119          if (!pSamplerChannel->GetMidiInputDevice()) throw LinuxSamplerException("No MIDI input device connected yet");          // Driver type name aliasing...
1120          pSamplerChannel->GetMidiInputDevice()->SetInputPort(MIDIInputPort.c_str());          if (AudioOutputDriver == "ALSA") AudioOutputDriver = "Alsa";
1121            if (AudioOutputDriver == "JACK") AudioOutputDriver = "Jack";
1122            // Check if there's one audio output device already created
1123            // for the intended audio driver type (AudioOutputDriver)...
1124            AudioOutputDevice *pDevice = NULL;
1125            std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1126            std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1127            for (; iter != devices.end(); iter++) {
1128                if ((iter->second)->Driver() == AudioOutputDriver) {
1129                    pDevice = iter->second;
1130                    break;
1131                }
1132            }
1133            // If it doesn't exist, create a new one with default parameters...
1134            if (pDevice == NULL) {
1135                std::map<String,String> params;
1136                pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1137            }
1138            // Must have a device...
1139            if (pDevice == NULL)
1140                throw LinuxSamplerException("Internal error: could not create audio output device.");
1141            // Set it as the current channel device...
1142            pSamplerChannel->SetAudioOutputDevice(pDevice);
1143        }
1144        catch (LinuxSamplerException e) {
1145             result.Error(e);
1146        }
1147        return result.Produce();
1148    }
1149    
1150    String LSCPServer::SetMIDIInputPort(uint MIDIPort, uint uiSamplerChannel) {
1151        dmsg(2,("LSCPServer: SetMIDIInputPort(MIDIPort=%d, SamplerChannel=%d)\n",MIDIPort,uiSamplerChannel));
1152        LSCPResultSet result;
1153        try {
1154            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1155            if (!pSamplerChannel) throw LinuxSamplerException("Invalid channel number " + ToString(uiSamplerChannel));
1156            pSamplerChannel->SetMidiInputPort(MIDIPort);
1157      }      }
1158      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
1159           result.Error(e);           result.Error(e);
# Line 606  String LSCPServer::SetMIDIInputPort(Stri Line 1161  String LSCPServer::SetMIDIInputPort(Stri
1161      return result.Produce();      return result.Produce();
1162  }  }
1163    
 /**  
  * Will be called by the parser to change the MIDI input channel on which the  
  * engine of a particular sampler channel should listen to.  
  */  
1164  String LSCPServer::SetMIDIInputChannel(uint MIDIChannel, uint uiSamplerChannel) {  String LSCPServer::SetMIDIInputChannel(uint MIDIChannel, uint uiSamplerChannel) {
1165      dmsg(2,("LSCPServer: SetMIDIInputChannel(MIDIChannel=%d, SamplerChannel=%d)\n", MIDIChannel, uiSamplerChannel));      dmsg(2,("LSCPServer: SetMIDIInputChannel(MIDIChannel=%d, SamplerChannel=%d)\n",MIDIChannel,uiSamplerChannel));
1166      LSCPResultSet result;      LSCPResultSet result;
1167      try {      try {
1168          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1169          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw LinuxSamplerException("Invalid channel number " + ToString(uiSamplerChannel));
1170          if (!pSamplerChannel->GetMidiInputDevice()) throw LinuxSamplerException("No MIDI input device connected yet");          pSamplerChannel->SetMidiInputChannel((MidiInputPort::midi_chan_t) MIDIChannel);
         MidiInputDevice::type_t oldtype = pSamplerChannel->GetMidiInputDevice()->Type();  
         pSamplerChannel->SetMidiInputDevice(oldtype, (MidiInputDevice::midi_chan_t) MIDIChannel);  
1171      }      }
1172      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
1173           result.Error(e);           result.Error(e);
# Line 626  String LSCPServer::SetMIDIInputChannel(u Line 1175  String LSCPServer::SetMIDIInputChannel(u
1175      return result.Produce();      return result.Produce();
1176  }  }
1177    
1178  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint SamplerChannel) {  String LSCPServer::SetMIDIInputDevice(uint MIDIDeviceId, uint uiSamplerChannel) {
1179        dmsg(2,("LSCPServer: SetMIDIInputDevice(MIDIDeviceId=%d, SamplerChannel=%d)\n",MIDIDeviceId,uiSamplerChannel));
1180      LSCPResultSet result;      LSCPResultSet result;
1181      try {      try {
1182          throw LinuxSamplerException("Command not yet implemented");          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1183            if (!pSamplerChannel) throw LinuxSamplerException("Invalid channel number " + ToString(uiSamplerChannel));
1184            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1185            if (!devices.count(MIDIDeviceId)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1186            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1187            pSamplerChannel->SetMidiInputDevice(pDevice);
1188        }
1189        catch (LinuxSamplerException e) {
1190             result.Error(e);
1191        }
1192        return result.Produce();
1193    }
1194    
1195    String LSCPServer::SetMIDIInputType(String MidiInputDriver, uint uiSamplerChannel) {
1196        dmsg(2,("LSCPServer: SetMIDIInputType(String MidiInputDriver=%s, SamplerChannel=%d)\n",MidiInputDriver.c_str(),uiSamplerChannel));
1197        LSCPResultSet result;
1198        try {
1199            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1200            if (!pSamplerChannel) throw LinuxSamplerException("Invalid channel number " + ToString(uiSamplerChannel));
1201            // Driver type name aliasing...
1202            if (MidiInputDriver == "ALSA") MidiInputDriver = "Alsa";
1203            // Check if there's one MIDI input device already created
1204            // for the intended MIDI driver type (MidiInputDriver)...
1205            MidiInputDevice *pDevice = NULL;
1206            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1207            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
1208            for (; iter != devices.end(); iter++) {
1209                if ((iter->second)->Driver() == MidiInputDriver) {
1210                    pDevice = iter->second;
1211                    break;
1212                }
1213            }
1214            // If it doesn't exist, create a new one with default parameters...
1215            if (pDevice == NULL) {
1216                std::map<String,String> params;
1217                pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1218                // Make it with at least one initial port.
1219                std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1220                parameters["PORTS"]->SetValue("1");
1221            }
1222            // Must have a device...
1223            if (pDevice == NULL)
1224                throw LinuxSamplerException("Internal error: could not create MIDI input device.");
1225            // Set it as the current channel device...
1226            pSamplerChannel->SetMidiInputDevice(pDevice);
1227        }
1228        catch (LinuxSamplerException e) {
1229             result.Error(e);
1230        }
1231        return result.Produce();
1232    }
1233    
1234    /**
1235     * Will be called by the parser to change the MIDI input device, port and channel on which
1236     * engine of a particular sampler channel should listen to.
1237     */
1238    String LSCPServer::SetMIDIInput(uint MIDIDeviceId, uint MIDIPort, uint MIDIChannel, uint uiSamplerChannel) {
1239        dmsg(2,("LSCPServer: SetMIDIInput(MIDIDeviceId=%d, MIDIPort=%d, MIDIChannel=%d, SamplerChannel=%d)\n", MIDIDeviceId, MIDIPort, MIDIChannel, uiSamplerChannel));
1240        LSCPResultSet result;
1241        try {
1242            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1243            if (!pSamplerChannel) throw LinuxSamplerException("Invalid channel number " + ToString(uiSamplerChannel));
1244            std::map<uint, MidiInputDevice*> devices =  pSampler->GetMidiInputDevices();
1245            if (!devices.count(MIDIDeviceId)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1246            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1247            pSamplerChannel->SetMidiInput(pDevice, MIDIPort, (MidiInputPort::midi_chan_t) MIDIChannel);
1248      }      }
1249      catch (LinuxSamplerException e) {      catch (LinuxSamplerException e) {
1250           result.Error(e);           result.Error(e);
# Line 677  String LSCPServer::ResetChannel(uint uiS Line 1292  String LSCPServer::ResetChannel(uint uiS
1292  }  }
1293    
1294  /**  /**
1295     * Will be called by the parser to reset the whole sampler.
1296     */
1297    String LSCPServer::ResetSampler() {
1298        dmsg(2,("LSCPServer: ResetSampler()\n"));
1299        pSampler->Reset();
1300        LSCPResultSet result;
1301        return result.Produce();
1302    }
1303    
1304    /**
1305   * 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
1306   * server for receiving event messages.   * server for receiving event messages.
1307   */   */
1308  String LSCPServer::SubscribeNotification(uint UDPPort) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
1309      dmsg(2,("LSCPServer: SubscribeNotification(UDPPort=%d)\n", UDPPort));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
1310      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
1311        SubscriptionMutex.Lock();
1312        eventSubscriptions[type].push_back(currentSocket);
1313        SubscriptionMutex.Unlock();
1314        return result.Produce();
1315  }  }
1316    
1317  /**  /**
1318   * 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
1319   * for not receiving further event messages.   * for not receiving further event messages.
1320   */   */
1321  String LSCPServer::UnsubscribeNotification(String SessionID) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
1322      dmsg(2,("LSCPServer: UnsubscribeNotification(SessionID=%s)\n", SessionID.c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
1323      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
1324        SubscriptionMutex.Lock();
1325        eventSubscriptions[type].remove(currentSocket);
1326        SubscriptionMutex.Unlock();
1327        return result.Produce();
1328    }
1329    
1330    /**
1331     * Will be called by the parser to enable or disable echo mode; if echo
1332     * mode is enabled, all commands from the client will (immediately) be
1333     * echoed back to the client.
1334     */
1335    String LSCPServer::SetEcho(yyparse_param_t* pSession, double boolean_value) {
1336        dmsg(2,("LSCPServer: SetEcho(val=%f)\n", boolean_value));
1337        LSCPResultSet result;
1338        try {
1339            if      (boolean_value == 0) pSession->bVerbose = false;
1340            else if (boolean_value == 1) pSession->bVerbose = true;
1341            else throw LinuxSamplerException("Not a boolean value, must either be 0 or 1");
1342        }
1343        catch (LinuxSamplerException e) {
1344             result.Error(e);
1345        }
1346        return result.Produce();
1347    }
1348    
1349    // Instrument loader constructor.
1350    LSCPLoadInstrument::LSCPLoadInstrument(Engine* pEngine, String Filename, uint uiInstrument)
1351        : Thread(false, 0, -4)
1352    {
1353        this->pEngine = pEngine;
1354        this->Filename = Filename;
1355        this->uiInstrument = uiInstrument;
1356    }
1357    
1358    // Instrument loader process.
1359    int LSCPLoadInstrument::Main()
1360    {
1361        try {
1362            pEngine->LoadInstrument(Filename.c_str(), uiInstrument);
1363        }
1364    
1365        catch (LinuxSamplerException e) {
1366            e.PrintMessage();
1367        }
1368    
1369        // Always re-enable the engine.
1370        pEngine->Enable();
1371    
1372        // FIXME: Shoot ourselves on the foot?
1373        delete this;
1374  }  }

Legend:
Removed from v.123  
changed lines
  Added in v.223

  ViewVC Help
Powered by ViewVC