/[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 1350 by iliev, Sun Sep 16 23:06:10 2007 UTC revision 2535 by schoenebeck, Tue Apr 15 19:35:35 2014 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2014 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    #include <string>
26    
27    #include "../common/File.h"
28  #include "lscpserver.h"  #include "lscpserver.h"
29  #include "lscpresultset.h"  #include "lscpresultset.h"
30  #include "lscpevent.h"  #include "lscpevent.h"
31    
32    #if defined(WIN32)
33    #include <windows.h>
34    #else
35  #include <fcntl.h>  #include <fcntl.h>
36    #endif
37    
38  #if ! HAVE_SQLITE3  #if ! HAVE_SQLITE3
39  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
# Line 35  Line 43 
43  #include "../engines/EngineChannelFactory.h"  #include "../engines/EngineChannelFactory.h"
44  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
45  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
46    #include "../effects/EffectFactory.h"
47    
48    namespace LinuxSampler {
49    
50    String lscpParserProcessShellInteraction(String& line, yyparse_param_t* param, bool possibilities);
51    
52    /**
53     * Returns a copy of the given string where all special characters are
54     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
55     * to escape LSCP response fields in case the respective response field is
56     * actually defined as using escape sequences in the LSCP specs.
57     *
58     * @e Caution: DO NOT use this function for escaping path based responses,
59     * use the Path class (src/common/Path.h) for this instead!
60     */
61    static String _escapeLscpResponse(String txt) {
62        for (int i = 0; i < txt.length(); i++) {
63            const char c = txt.c_str()[i];
64            if (
65                !(c >= '0' && c <= '9') &&
66                !(c >= 'a' && c <= 'z') &&
67                !(c >= 'A' && c <= 'Z') &&
68                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
69                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
70                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
71                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
72                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
73                !(c == '@') && !(c == '[') && !(c == ']') &&
74                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
75                !(c == '|') && !(c == '}') && !(c == '~')
76            ) {
77                // convert the "special" character into a "\xHH" LSCP escape sequence
78                char buf[5];
79                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
80                txt.replace(i, 1, buf);
81                i += 3;
82            }
83        }
84        return txt;
85    }
86    
87  /**  /**
88   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
# Line 51  Line 99 
99   */   */
100  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
101  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
102  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions;
103  std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();  std::vector<yyparse_param_t>::iterator itCurrentSession;
104  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies;
105  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands;
106  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions;
107  Mutex LSCPServer::NotifyMutex = Mutex();  Mutex LSCPServer::NotifyMutex;
108  Mutex LSCPServer::NotifyBufferMutex = Mutex();  Mutex LSCPServer::NotifyBufferMutex;
109  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex;
110  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex;
111    
112  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4) {  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) {
113      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
114      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
115      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 87  LSCPServer::LSCPServer(Sampler* pSampler Line 135  LSCPServer::LSCPServer(Sampler* pSampler
135      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
136      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
137      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
138        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
139      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
140      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
141        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
142        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
143        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_count, "EFFECT_INSTANCE_COUNT");
144        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_info, "EFFECT_INSTANCE_INFO");
145        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_count, "SEND_EFFECT_CHAIN_COUNT");
146        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_info, "SEND_EFFECT_CHAIN_INFO");
147      hSocket = -1;      hSocket = -1;
148  }  }
149    
150  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
151        CloseAllConnections();
152        InstrumentManager::StopBackgroundThread();
153    #if defined(WIN32)
154        if (hSocket >= 0) closesocket(hSocket);
155    #else
156      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
157    #endif
158    }
159    
160    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
161        this->pParent = pParent;
162    }
163    
164    LSCPServer::EventHandler::~EventHandler() {
165        std::vector<midi_listener_entry> l = channelMidiListeners;
166        channelMidiListeners.clear();
167        for (int i = 0; i < l.size(); i++)
168            delete l[i].pMidiListener;
169  }  }
170    
171  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
172      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
173  }  }
174    
175    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
176        pChannel->AddEngineChangeListener(this);
177    }
178    
179    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
180        if (!pChannel->GetEngineChannel()) return;
181        EngineToBeChanged(pChannel->Index());
182    }
183    
184    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
185        SamplerChannel* pSamplerChannel =
186            pParent->pSampler->GetSamplerChannel(ChannelId);
187        if (!pSamplerChannel) return;
188        EngineChannel* pEngineChannel =
189            pSamplerChannel->GetEngineChannel();
190        if (!pEngineChannel) return;
191        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
192            if ((*iter).pEngineChannel == pEngineChannel) {
193                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
194                pEngineChannel->Disconnect(pMidiListener);
195                channelMidiListeners.erase(iter);
196                delete pMidiListener;
197                return;
198            }
199        }
200    }
201    
202    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
203        SamplerChannel* pSamplerChannel =
204            pParent->pSampler->GetSamplerChannel(ChannelId);
205        if (!pSamplerChannel) return;
206        EngineChannel* pEngineChannel =
207            pSamplerChannel->GetEngineChannel();
208        if (!pEngineChannel) return;
209        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
210        pEngineChannel->Connect(pMidiListener);
211        midi_listener_entry entry = {
212            pSamplerChannel, pEngineChannel, pMidiListener
213        };
214        channelMidiListeners.push_back(entry);
215    }
216    
217  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
218      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
219  }  }
# Line 108  void LSCPServer::EventHandler::MidiDevic Line 222  void LSCPServer::EventHandler::MidiDevic
222      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
223  }  }
224    
225    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
226        pDevice->RemoveMidiPortCountListener(this);
227        for (int i = 0; i < pDevice->PortCount(); ++i)
228            MidiPortToBeRemoved(pDevice->GetPort(i));
229    }
230    
231    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
232        pDevice->AddMidiPortCountListener(this);
233        for (int i = 0; i < pDevice->PortCount(); ++i)
234            MidiPortAdded(pDevice->GetPort(i));
235    }
236    
237    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
238        // yet unused
239    }
240    
241    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
242        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
243            if ((*iter).pPort == pPort) {
244                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
245                pPort->Disconnect(pMidiListener);
246                deviceMidiListeners.erase(iter);
247                delete pMidiListener;
248                return;
249            }
250        }
251    }
252    
253    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
254        // find out the device ID
255        std::map<uint, MidiInputDevice*> devices =
256            pParent->pSampler->GetMidiInputDevices();
257        for (
258            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
259            iter != devices.end(); ++iter
260        ) {
261            if (iter->second == pPort->GetDevice()) { // found
262                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
263                pPort->Connect(pMidiListener);
264                device_midi_listener_entry entry = {
265                    pPort, pMidiListener, iter->first
266                };
267                deviceMidiListeners.push_back(entry);
268                return;
269            }
270        }
271    }
272    
273  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
274      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
275  }  }
# Line 144  void LSCPServer::EventHandler::TotalVoic Line 306  void LSCPServer::EventHandler::TotalVoic
306      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
307  }  }
308    
309    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
310        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
311    }
312    
313  #if HAVE_SQLITE3  #if HAVE_SQLITE3
314  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
315      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
# Line 178  void LSCPServer::DbInstrumentsEventHandl Line 344  void LSCPServer::DbInstrumentsEventHandl
344  }  }
345  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
346    
347    void LSCPServer::RemoveListeners() {
348        pSampler->RemoveChannelCountListener(&eventHandler);
349        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
350        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
351        pSampler->RemoveVoiceCountListener(&eventHandler);
352        pSampler->RemoveStreamCountListener(&eventHandler);
353        pSampler->RemoveBufferFillListener(&eventHandler);
354        pSampler->RemoveTotalStreamCountListener(&eventHandler);
355        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
356        pSampler->RemoveFxSendCountListener(&eventHandler);
357        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
358        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
359        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
360        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
361    #if HAVE_SQLITE3
362        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
363    #endif
364    }
365    
366  /**  /**
367   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 194  int LSCPServer::WaitUntilInitialized(lon Line 378  int LSCPServer::WaitUntilInitialized(lon
378  }  }
379    
380  int LSCPServer::Main() {  int LSCPServer::Main() {
381            #if defined(WIN32)
382            WSADATA wsaData;
383            int iResult;
384            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
385            if (iResult != 0) {
386                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
387                    exit(EXIT_FAILURE);
388            }
389            #endif
390      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
391      if (hSocket < 0) {      if (hSocket < 0) {
392          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 207  int LSCPServer::Main() { Line 400  int LSCPServer::Main() {
400              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
401                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
402                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
403                        #if defined(WIN32)
404                        closesocket(hSocket);
405                        #else
406                      close(hSocket);                      close(hSocket);
407                        #endif
408                      //return -1;                      //return -1;
409                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
410                  }                  }
# Line 227  int LSCPServer::Main() { Line 424  int LSCPServer::Main() {
424      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
425      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
426      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
427        pSampler->AddTotalStreamCountListener(&eventHandler);
428      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
429      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
430      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
# Line 246  int LSCPServer::Main() { Line 444  int LSCPServer::Main() {
444      timeval timeout;      timeval timeout;
445    
446      while (true) {      while (true) {
447            #if CONFIG_PTHREAD_TESTCANCEL
448                    TestCancel();
449            #endif
450          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
451          {          {
452                LockGuard lock(EngineChannelFactory::EngineChannelsMutex);
453              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
454              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
455              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
456              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
457                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
458                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
459                  }                  }
460    
461                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
462                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
463                      if(fxs != NULL && fxs->IsInfoChanged()) {                      if(fxs != NULL && fxs->IsInfoChanged()) {
464                          int chn = (*itEngineChannel)->iSamplerChannelIndex;                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
465                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
466                          fxs->SetInfoChanged(false);                          fxs->SetInfoChanged(false);
467                      }                      }
# Line 267  int LSCPServer::Main() { Line 469  int LSCPServer::Main() {
469              }              }
470          }          }
471    
472          //Now let's deliver late notifies (if any)          // check if MIDI data arrived on some engine channel
473          NotifyBufferMutex.Lock();          for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
474          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {              const EventHandler::midi_listener_entry entry =
475                    eventHandler.channelMidiListeners[i];
476                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
477                if (pMidiListener->NotesChanged()) {
478                    for (int iNote = 0; iNote < 128; iNote++) {
479                        if (pMidiListener->NoteChanged(iNote)) {
480                            const bool bActive = pMidiListener->NoteIsActive(iNote);
481                            LSCPServer::SendLSCPNotify(
482                                LSCPEvent(
483                                    LSCPEvent::event_channel_midi,
484                                    entry.pSamplerChannel->Index(),
485                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
486                                    iNote,
487                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
488                                            : pMidiListener->NoteOffVelocity(iNote)
489                                )
490                            );
491                        }
492                    }
493                }
494            }
495    
496            // check if MIDI data arrived on some MIDI device
497            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
498                const EventHandler::device_midi_listener_entry entry =
499                    eventHandler.deviceMidiListeners[i];
500                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
501                if (pMidiListener->NotesChanged()) {
502                    for (int iNote = 0; iNote < 128; iNote++) {
503                        if (pMidiListener->NoteChanged(iNote)) {
504                            const bool bActive = pMidiListener->NoteIsActive(iNote);
505                            LSCPServer::SendLSCPNotify(
506                                LSCPEvent(
507                                    LSCPEvent::event_device_midi,
508                                    entry.uiDeviceID,
509                                    entry.pPort->GetPortNumber(),
510                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
511                                    iNote,
512                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
513                                            : pMidiListener->NoteOffVelocity(iNote)
514                                )
515                            );
516                        }
517                    }
518                }
519            }
520    
521            //Now let's deliver late notifies (if any)
522            {
523                LockGuard lock(NotifyBufferMutex);
524                for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
525  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
526                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);
527  #else  #else
528                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
529  #endif  #endif
530          }              }
531          bufferedNotifies.clear();              bufferedNotifies.clear();
532          NotifyBufferMutex.Unlock();          }
533    
534          fd_set selectSet = fdSet;          fd_set selectSet = fdSet;
535          timeout.tv_sec  = 0;          timeout.tv_sec  = 0;
# Line 285  int LSCPServer::Main() { Line 537  int LSCPServer::Main() {
537    
538          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
539    
540          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
541                  continue; //Nothing try again                  continue; //Nothing try again
542          if (retval == -1) {          if (retval == -1) {
543                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
544                    #if defined(WIN32)
545                    closesocket(hSocket);
546                    #else
547                  close(hSocket);                  close(hSocket);
548                    #endif
549                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
550          }          }
551    
# Line 301  int LSCPServer::Main() { Line 557  int LSCPServer::Main() {
557                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
558                  }                  }
559    
560                    #if defined(WIN32)
561                    u_long nonblock_io = 1;
562                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
563                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
564                      exit(EXIT_FAILURE);
565                    }
566            #else
567                    struct linger linger;
568                    linger.l_onoff = 1;
569                    linger.l_linger = 0;
570                    if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) {
571                        std::cerr << "LSCPServer: Failed to set SO_LINGER\n";
572                    }
573    
574                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
575                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
576                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
577                  }                  }
578                    #endif
579    
580                  // Parser initialization                  // Parser initialization
581                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 323  int LSCPServer::Main() { Line 594  int LSCPServer::Main() {
594          //Something was selected and it was not the hSocket, so it must be some command(s) coming.          //Something was selected and it was not the hSocket, so it must be some command(s) coming.
595          for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {          for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {
596                  if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?                  if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?
597                            currentSocket = (*iter).hSession;  //a hack
598                          if (GetLSCPCommand(iter)) {     //Have we read the entire command?                          if (GetLSCPCommand(iter)) {     //Have we read the entire command?
599                                  dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));                                  dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));
600                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
601                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
                                 currentSocket = (*iter).hSession;  //a hack  
602                                  itCurrentSession = iter; // another hack                                  itCurrentSession = iter; // another hack
603                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
604                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
# Line 341  int LSCPServer::Main() { Line 612  int LSCPServer::Main() {
612                                          CloseConnection(iter);                                          CloseConnection(iter);
613                                  }                                  }
614                          }                          }
615                            currentSocket = -1;     //continuation of a hack
616                          //socket may have been closed, iter may be invalid, get out of the loop for now.                          //socket may have been closed, iter may be invalid, get out of the loop for now.
617                          //we'll be back if there is data.                          //we'll be back if there is data.
618                          break;                          break;
# Line 355  void LSCPServer::CloseConnection( std::v Line 627  void LSCPServer::CloseConnection( std::v
627          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
628          Sessions.erase(iter);          Sessions.erase(iter);
629          FD_CLR(socket,  &fdSet);          FD_CLR(socket,  &fdSet);
630          SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)          {
631          for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {              LockGuard lock(SubscriptionMutex);
632                  iter->second.remove(socket);              // Must unsubscribe this socket from all events (if any)
633          }              for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {
634          SubscriptionMutex.Unlock();                  iter->second.remove(socket);
635          NotifyMutex.Lock();              }
636            }
637            LockGuard lock(NotifyMutex);
638          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
639          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
640            #if defined(WIN32)
641            closesocket(socket);
642            #else
643          close(socket);          close(socket);
644          NotifyMutex.Unlock();          #endif
645    }
646    
647    void LSCPServer::CloseAllConnections() {
648        std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
649        while(iter != Sessions.end()) {
650            CloseConnection(iter);
651            iter = Sessions.begin();
652        }
653  }  }
654    
655  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
656          int subs = 0;          int subs = 0;
657          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
658          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();
659                          iter != events.end(); iter++)                          iter != events.end(); iter++)
660          {          {
661                  subs += eventSubscriptions.count(*iter);                  subs += eventSubscriptions.count(*iter);
662          }          }
         SubscriptionMutex.Unlock();  
663          return subs;          return subs;
664  }  }
665    
666  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
667          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
668          if (eventSubscriptions.count(event.GetType()) == 0) {          if (eventSubscriptions.count(event.GetType()) == 0) {
669                  SubscriptionMutex.Unlock();     //Nobody is subscribed to this event                  // Nobody is subscribed to this event
670                  return;                  return;
671          }          }
672          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
# Line 408  void LSCPServer::SendLSCPNotify( LSCPEve Line 692  void LSCPServer::SendLSCPNotify( LSCPEve
692                          }                          }
693                  }                  }
694          }          }
         SubscriptionMutex.Unlock();  
695  }  }
696    
697  extern int GetLSCPCommand( void *buf, int max_size ) {  extern int GetLSCPCommand( void *buf, int max_size ) {
# Line 433  extern yyparse_param_t* GetCurrentYaccSe Line 716  extern yyparse_param_t* GetCurrentYaccSe
716  }  }
717    
718  /**  /**
719     * Generate the relevant LSCP documentation reference section if necessary.
720     * The documentation section for the currently active command on the LSCP
721     * shell's command line will be encoded in a special format, specifically for
722     * the LSCP shell application.
723     *
724     * @param line - current LSCP command line
725     * @param param - reentrant Bison parser parameters
726     *
727     * @return encoded reference string or empty string if nothing shall be sent
728     *         to LSCP shell (client) at this point
729     */
730    String LSCPServer::generateLSCPDocReply(const String& line, yyparse_param_t* param) {
731        String result;
732        lscp_ref_entry_t* ref = lscp_reference_for_command(line.c_str());
733        // Pointer comparison works here, since the function above always
734        // returns the same constant pointer for the respective LSCP
735        // command ... Only send the LSCP reference section to the client if
736        // another LSCP reference section became relevant now:
737        if (ref != param->pLSCPDocRef) {
738            param->pLSCPDocRef = ref;
739            if (ref) { // send a new LSCP doc section to client ...
740                result += "SHD:" + ToString(LSCP_SHD_MATCH) + ":" + String(ref->name) + "\n";
741                result += String(ref->section) + "\n";
742                result += "."; // dot line marks the end of the text for client
743            } else { // inform client that no LSCP doc section matches right now ...
744                result = "SHD:" + ToString(LSCP_SHD_NO_MATCH);
745            }
746        }
747        dmsg(4,("LSCP doc reply -> '%s'\n", result.c_str()));
748        return result;
749    }
750    
751    /**
752   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
753   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
754   * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.   * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.
755   */   */
756  bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {  bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {
757          int socket = (*iter).hSession;          int socket = (*iter).hSession;
758            int result;
759          char c;          char c;
760          int i = 0;          std::vector<char> input;
761    
762            // first get as many character as possible and add it to the 'input' buffer
763          while (true) {          while (true) {
764                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  #if defined(WIN32)
765                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
766                          CloseConnection(iter);                  #else
767                          break;                  result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
768                    #endif
769                    if (result == 1) input.push_back(c);
770                    else break; // end of input or some error
771                    if (c == '\n') break; // process line by line
772            }
773    
774            // process input buffer
775            for (int i = 0; i < input.size(); ++i) {
776                    c = input[i];
777                    if (c == '\r') continue; //Ignore CR
778                    if (c == '\n') {
779                            // only if the other side is the LSCP shell application:
780                            // check the current (incomplete) command line for syntax errors,
781                            // possible completions and report everything back to the shell
782                            if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) {
783                                    String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), false);
784                                    if (!s.empty() && (*iter).bShellInteract) AnswerClient(s + "\n");
785                            }
786                            // if other side is LSCP shell application, send the relevant LSCP
787                            // documentation section of the current command line (if necessary)
788                            if ((*iter).bShellSendLSCPDoc && (*iter).bShellInteract) {
789                                    String s = generateLSCPDocReply(bufferedCommands[socket], &(*iter));
790                                    if (!s.empty()) AnswerClient(s + "\n");
791                            }
792                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
793                            bufferedCommands[socket] += "\r\n";
794                            return true; //Complete command was read
795                    } else if (c == 2) { // custom ASCII code usage for moving cursor left (LSCP shell)
796                            if (iter->iCursorOffset + bufferedCommands[socket].size() > 0)
797                                    iter->iCursorOffset--;
798                    } else if (c == 3) { // custom ASCII code usage for moving cursor right (LSCP shell)
799                            if (iter->iCursorOffset < 0) iter->iCursorOffset++;
800                    } else {
801                            size_t cursorPos = bufferedCommands[socket].size() + iter->iCursorOffset;
802                            // backspace character - should only happen with shell
803                            if (c == '\b') {
804                                    if (!bufferedCommands[socket].empty() && cursorPos > 0)
805                                            bufferedCommands[socket].erase(cursorPos - 1, 1);
806                            } else { // append (or insert) new character (at current cursor position) ...
807                                    if (cursorPos >= 0)
808                                            bufferedCommands[socket].insert(cursorPos, String(1,c)); // insert
809                                    else
810                                            bufferedCommands[socket] += c; // append
811                            }
812                  }                  }
813                  if (result == 1) {                  // Only if the other side (client) is the LSCP shell application:
814                          if (c == '\r')                  // The following block takes care about automatic correction, auto
815                                  continue; //Ignore CR                  // completion (and suggestions), LSCP reference documentation, etc.
816                          if (c == '\n') {                  // The "if" statement here is for optimization reasons, so that the
817                                  LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));                  // heavy LSCP grammar evaluation algorithm is only executed once for an
818                                  bufferedCommands[socket] += "\r\n";                  // entire command line received.
819                                  return true; //Complete command was read                  if (i == input.size() - 1) {
820                            // check the current (incomplete) command line for syntax errors,
821                            // possible completions and report everything back to the shell
822                            if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) {
823                                    String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), true);
824                                    if (!s.empty() && (*iter).bShellInteract && i == input.size() - 1)
825                                            AnswerClient(s + "\n");
826                            }
827                            // if other side is LSCP shell application, send the relevant LSCP
828                            // documentation section of the current command line (if necessary)
829                            if ((*iter).bShellSendLSCPDoc && (*iter).bShellInteract) {
830                                    String s = generateLSCPDocReply(bufferedCommands[socket], &(*iter));
831                                    if (!s.empty()) AnswerClient(s + "\n");
832                          }                          }
                         bufferedCommands[socket] += c;  
833                  }                  }
834                  if (result == -1) {          }
835                          if (errno == EAGAIN) //Would block, try again later.  
836            // handle network errors ...
837            if (result == 0) { //socket was selected, so 0 here means client has closed the connection
838                    CloseConnection(iter);
839                    return false;
840            }
841            #if defined(WIN32)
842            if (result == SOCKET_ERROR) {
843                    int wsa_lasterror = WSAGetLastError();
844                    if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
845                            return false;
846                    dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
847                    CloseConnection(iter);
848                    return false;
849            }
850            #else
851            if (result == -1) {
852                    if (errno == EAGAIN) //Would block, try again later.
853                            return false;
854                    switch(errno) {
855                            case EBADF:
856                                    dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
857                                    return false;
858                            case ECONNREFUSED:
859                                    dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
860                                    return false;
861                            case ENOTCONN:
862                                    dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));
863                                    return false;
864                            case ENOTSOCK:
865                                    dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
866                                    return false;
867                            case EAGAIN:
868                                    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"));
869                                    return false;
870                            case EINTR:
871                                    dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
872                                    return false;
873                            case EFAULT:
874                                    dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
875                                    return false;
876                            case EINVAL:
877                                    dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
878                                    return false;
879                            case ENOMEM:
880                                    dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
881                                    return false;
882                            default:
883                                    dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
884                                  return false;                                  return false;
                         switch(errno) {  
                                 case EBADF:  
                                         dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));  
                                         break;  
                                 case ECONNREFUSED:  
                                         dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));  
                                         break;  
                                 case ENOTCONN:  
                                         dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));  
                                         break;  
                                 case ENOTSOCK:  
                                         dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));  
                                         break;  
                                 case EAGAIN:  
                                         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"));  
                                         break;  
                                 case EINTR:  
                                         dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));  
                                         break;  
                                 case EFAULT:  
                                         dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));  
                                         break;  
                                 case EINVAL:  
                                         dmsg(2,("LSCPScanner: Invalid argument passed.\n"));  
                                         break;  
                                 case ENOMEM:  
                                         dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));  
                                         break;  
                                 default:  
                                         dmsg(2,("LSCPScanner: Unknown recv() error.\n"));  
                                         break;  
                         }  
                         CloseConnection(iter);  
                         break;  
885                  }                  }
886                    CloseConnection(iter);
887                    return false;
888          }          }
889            #endif
890    
891          return false;          return false;
892  }  }
893    
# Line 506  bool LSCPServer::GetLSCPCommand( std::ve Line 898  bool LSCPServer::GetLSCPCommand( std::ve
898   * @param ReturnMessage - message that will be send to the client   * @param ReturnMessage - message that will be send to the client
899   */   */
900  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
901      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage='%s')", ReturnMessage.c_str()));
902      if (currentSocket != -1) {      if (currentSocket != -1) {
903              NotifyMutex.Lock();              LockGuard lock(NotifyMutex);
904    
905            // just if other side is LSCP shell: in case respose is a multi-line
906            // one, then inform client about it before sending the actual mult-line
907            // response
908            if (GetCurrentYaccSession()->bShellInteract) {
909                // check if this is a multi-line response
910                int n = 0;
911                for (int i = 0; i < ReturnMessage.size(); ++i)
912                    if (ReturnMessage[i] == '\n') ++n;
913                if (n >= 2) {
914                    dmsg(2,("LSCP Shell <- expect mult-line response\n"));
915                    String s = LSCP_SHK_EXPECT_MULTI_LINE "\r\n";
916    #ifdef MSG_NOSIGNAL
917                    send(currentSocket, s.c_str(), s.size(), MSG_NOSIGNAL);
918    #else
919                    send(currentSocket, s.c_str(), s.size(), 0);
920    #endif                
921                }
922            }
923    
924  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
925              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
926  #else  #else
927              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
928  #endif  #endif
             NotifyMutex.Unlock();  
929      }      }
930  }  }
931    
# Line 664  String LSCPServer::SetEngineType(String Line 1075  String LSCPServer::SetEngineType(String
1075      try {      try {
1076          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1077          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1078          LockRTNotify();          LockGuard lock(RTNotifyMutex);
1079          pSamplerChannel->SetEngineType(EngineName);          pSamplerChannel->SetEngineType(EngineName);
1080          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
         UnlockRTNotify();  
1081      }      }
1082      catch (Exception e) {      catch (Exception e) {
1083           result.Error(e);           result.Error(e);
# Line 707  String LSCPServer::ListChannels() { Line 1117  String LSCPServer::ListChannels() {
1117   */   */
1118  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
1119      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
1120      LockRTNotify();      SamplerChannel* pSamplerChannel;
1121      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      {
1122      UnlockRTNotify();          LockGuard lock(RTNotifyMutex);
1123            pSamplerChannel = pSampler->AddSamplerChannel();
1124        }
1125      LSCPResultSet result(pSamplerChannel->Index());      LSCPResultSet result(pSamplerChannel->Index());
1126      return result.Produce();      return result.Produce();
1127  }  }
# Line 720  String LSCPServer::AddChannel() { Line 1132  String LSCPServer::AddChannel() {
1132  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
1133      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
1134      LSCPResultSet result;      LSCPResultSet result;
1135      LockRTNotify();      {
1136      pSampler->RemoveSamplerChannel(uiSamplerChannel);          LockGuard lock(RTNotifyMutex);
1137      UnlockRTNotify();          pSampler->RemoveSamplerChannel(uiSamplerChannel);
1138        }
1139      return result.Produce();      return result.Produce();
1140  }  }
1141    
# Line 765  String LSCPServer::ListAvailableEngines( Line 1178  String LSCPServer::ListAvailableEngines(
1178  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
1179      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
1180      LSCPResultSet result;      LSCPResultSet result;
1181      LockRTNotify();      {
1182      try {          LockGuard lock(RTNotifyMutex);
1183          Engine* pEngine = EngineFactory::Create(EngineName);          try {
1184          result.Add("DESCRIPTION", pEngine->Description());              Engine* pEngine = EngineFactory::Create(EngineName);
1185          result.Add("VERSION",     pEngine->Version());              result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1186          EngineFactory::Destroy(pEngine);              result.Add("VERSION",     pEngine->Version());
1187      }              EngineFactory::Destroy(pEngine);
1188      catch (Exception e) {          }
1189           result.Error(e);          catch (Exception e) {
1190                result.Error(e);
1191            }
1192      }      }
     UnlockRTNotify();  
1193      return result.Produce();      return result.Produce();
1194  }  }
1195    
# Line 841  String LSCPServer::GetChannelInfo(uint u Line 1255  String LSCPServer::GetChannelInfo(uint u
1255          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1256          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1257    
1258            // convert the filename into the correct encoding as defined for LSCP
1259            // (especially in terms of special characters -> escape sequences)
1260            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1261    #if WIN32
1262                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1263    #else
1264                // assuming POSIX
1265                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1266    #endif
1267            }
1268    
1269          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1270          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1271          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1272          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1273          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1274          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 863  String LSCPServer::GetVoiceCount(uint ui Line 1288  String LSCPServer::GetVoiceCount(uint ui
1288      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1289      LSCPResultSet result;      LSCPResultSet result;
1290      try {      try {
1291          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine loaded on sampler channel");  
1292          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1293          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1294      }      }
# Line 884  String LSCPServer::GetStreamCount(uint u Line 1306  String LSCPServer::GetStreamCount(uint u
1306      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1307      LSCPResultSet result;      LSCPResultSet result;
1308      try {      try {
1309          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1310          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1311          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1312      }      }
# Line 905  String LSCPServer::GetBufferFill(fill_re Line 1324  String LSCPServer::GetBufferFill(fill_re
1324      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1325      LSCPResultSet result;      LSCPResultSet result;
1326      try {      try {
1327          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1328          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1329          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1330          else {          else {
# Line 996  String LSCPServer::GetMidiInputDriverInf Line 1412  String LSCPServer::GetMidiInputDriverInf
1412              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1413                  if (s != "") s += ",";                  if (s != "") s += ",";
1414                  s += iter->first;                  s += iter->first;
1415                    delete iter->second;
1416              }              }
1417              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1418          }          }
# Line 1020  String LSCPServer::GetAudioOutputDriverI Line 1437  String LSCPServer::GetAudioOutputDriverI
1437              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1438                  if (s != "") s += ",";                  if (s != "") s += ",";
1439                  s += iter->first;                  s += iter->first;
1440                    delete iter->second;
1441              }              }
1442              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1443          }          }
# Line 1050  String LSCPServer::GetMidiInputDriverPar Line 1468  String LSCPServer::GetMidiInputDriverPar
1468          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1469          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1470          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1471            delete pParameter;
1472      }      }
1473      catch (Exception e) {      catch (Exception e) {
1474          result.Error(e);          result.Error(e);
# Line 1077  String LSCPServer::GetAudioOutputDriverP Line 1496  String LSCPServer::GetAudioOutputDriverP
1496          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1497          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1498          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1499            delete pParameter;
1500      }      }
1501      catch (Exception e) {      catch (Exception e) {
1502          result.Error(e);          result.Error(e);
# Line 1418  String LSCPServer::SetAudioOutputChannel Line 1838  String LSCPServer::SetAudioOutputChannel
1838  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1839      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1840      LSCPResultSet result;      LSCPResultSet result;
1841      LockRTNotify();      {
1842            LockGuard lock(RTNotifyMutex);
1843            try {
1844                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1845                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1846                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1847                if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1848                AudioOutputDevice* pDevice = devices[AudioDeviceId];
1849                pSamplerChannel->SetAudioOutputDevice(pDevice);
1850            }
1851            catch (Exception e) {
1852                result.Error(e);
1853            }
1854        }
1855        return result.Produce();
1856    }
1857    
1858    String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1859        dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1860        LSCPResultSet result;
1861        {
1862            LockGuard lock(RTNotifyMutex);
1863            try {
1864                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1865                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1866                // Driver type name aliasing...
1867                if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1868                if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1869                // Check if there's one audio output device already created
1870                // for the intended audio driver type (AudioOutputDriver)...
1871                AudioOutputDevice *pDevice = NULL;
1872                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1873                std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1874                for (; iter != devices.end(); iter++) {
1875                    if ((iter->second)->Driver() == AudioOutputDriver) {
1876                        pDevice = iter->second;
1877                        break;
1878                    }
1879                }
1880                // If it doesn't exist, create a new one with default parameters...
1881                if (pDevice == NULL) {
1882                    std::map<String,String> params;
1883                    pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1884                }
1885                // Must have a device...
1886                if (pDevice == NULL)
1887                    throw Exception("Internal error: could not create audio output device.");
1888                // Set it as the current channel device...
1889                pSamplerChannel->SetAudioOutputDevice(pDevice);
1890            }
1891            catch (Exception e) {
1892                result.Error(e);
1893            }
1894        }
1895        return result.Produce();
1896    }
1897    
1898    String LSCPServer::AddChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1899        dmsg(2,("LSCPServer: AddChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1900        LSCPResultSet result;
1901      try {      try {
1902          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1903          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1904          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();  
1905          if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1906          AudioOutputDevice* pDevice = devices[AudioDeviceId];          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1907          pSamplerChannel->SetAudioOutputDevice(pDevice);          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1908    
1909            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1910            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1911    
1912            pSamplerChannel->Connect(pPort);
1913        } catch (Exception e) {
1914            result.Error(e);
1915      }      }
1916      catch (Exception e) {      return result.Produce();
1917           result.Error(e);  }
1918    
1919    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel) {
1920        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d)\n",uiSamplerChannel));
1921        LSCPResultSet result;
1922        try {
1923            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1924            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1925            pSamplerChannel->DisconnectAllMidiInputPorts();
1926        } catch (Exception e) {
1927            result.Error(e);
1928      }      }
     UnlockRTNotify();  
1929      return result.Produce();      return result.Produce();
1930  }  }
1931    
1932  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {  String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId) {
1933      dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d)\n",uiSamplerChannel,MIDIDeviceId));
1934      LSCPResultSet result;      LSCPResultSet result;
     LockRTNotify();  
1935      try {      try {
1936          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1937          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1938          // Driver type name aliasing...  
1939          if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1940          if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1941          // Check if there's one audio output device already created          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1942          // for the intended audio driver type (AudioOutputDriver)...          
1943          AudioOutputDevice *pDevice = NULL;          std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1944          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          for (int i = 0; i < vPorts.size(); ++i)
1945          std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();              if (vPorts[i]->GetDevice() == pDevice)
1946          for (; iter != devices.end(); iter++) {                  pSamplerChannel->Disconnect(vPorts[i]);
1947              if ((iter->second)->Driver() == AudioOutputDriver) {  
1948                  pDevice = iter->second;      } catch (Exception e) {
1949                  break;          result.Error(e);
             }  
         }  
         // If it doesn't exist, create a new one with default parameters...  
         if (pDevice == NULL) {  
             std::map<String,String> params;  
             pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);  
         }  
         // Must have a device...  
         if (pDevice == NULL)  
             throw Exception("Internal error: could not create audio output device.");  
         // Set it as the current channel device...  
         pSamplerChannel->SetAudioOutputDevice(pDevice);  
1950      }      }
1951      catch (Exception e) {      return result.Produce();
1952           result.Error(e);  }
1953    
1954    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1955        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1956        LSCPResultSet result;
1957        try {
1958            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1959            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1960    
1961            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1962            if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1963            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1964    
1965            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1966            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1967    
1968            pSamplerChannel->Disconnect(pPort);
1969        } catch (Exception e) {
1970            result.Error(e);
1971        }
1972        return result.Produce();
1973    }
1974    
1975    String LSCPServer::ListChannelMidiInputs(uint uiSamplerChannel) {
1976        dmsg(2,("LSCPServer: ListChannelMidiInputs(uiSamplerChannel=%d)\n",uiSamplerChannel));
1977        LSCPResultSet result;
1978        try {
1979            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1980            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1981            std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1982    
1983            String s;
1984            for (int i = 0; i < vPorts.size(); ++i) {
1985                const int iDeviceID = vPorts[i]->GetDevice()->MidiInputDeviceID();
1986                const int iPortNr   = vPorts[i]->GetPortNumber();
1987                if (s.size()) s += ",";
1988                s += "{" + ToString(iDeviceID) + ","
1989                         + ToString(iPortNr) + "}";
1990            }
1991            result.Add(s);
1992        } catch (Exception e) {
1993            result.Error(e);
1994      }      }
     UnlockRTNotify();  
1995      return result.Produce();      return result.Produce();
1996  }  }
1997    
# Line 1543  String LSCPServer::SetMIDIInputType(Stri Line 2065  String LSCPServer::SetMIDIInputType(Stri
2065              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
2066              // Make it with at least one initial port.              // Make it with at least one initial port.
2067              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
             parameters["PORTS"]->SetValue("1");  
2068          }          }
2069          // Must have a device...          // Must have a device...
2070          if (pDevice == NULL)          if (pDevice == NULL)
# Line 1586  String LSCPServer::SetVolume(double dVol Line 2107  String LSCPServer::SetVolume(double dVol
2107      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
2108      LSCPResultSet result;      LSCPResultSet result;
2109      try {      try {
2110          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2111          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
2112      }      }
2113      catch (Exception e) {      catch (Exception e) {
# Line 1605  String LSCPServer::SetChannelMute(bool b Line 2123  String LSCPServer::SetChannelMute(bool b
2123      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
2124      LSCPResultSet result;      LSCPResultSet result;
2125      try {      try {
2126          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2127    
2128          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
2129          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1626  String LSCPServer::SetChannelSolo(bool b Line 2140  String LSCPServer::SetChannelSolo(bool b
2140      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
2141      LSCPResultSet result;      LSCPResultSet result;
2142      try {      try {
2143          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2144    
2145          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
2146          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
# Line 1750  String LSCPServer::GetMidiInstrumentMapp Line 2260  String LSCPServer::GetMidiInstrumentMapp
2260      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2261      LSCPResultSet result;      LSCPResultSet result;
2262      try {      try {
2263          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2264      } catch (Exception e) {      } catch (Exception e) {
2265          result.Error(e);          result.Error(e);
2266      }      }
# Line 1761  String LSCPServer::GetMidiInstrumentMapp Line 2271  String LSCPServer::GetMidiInstrumentMapp
2271  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2272      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2273      LSCPResultSet result;      LSCPResultSet result;
2274      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2275      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2276      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2277          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2278      }      }
     result.Add(totalMappings);  
2279      return result.Produce();      return result.Produce();
2280  }  }
2281    
# Line 1776  String LSCPServer::GetMidiInstrumentMapp Line 2283  String LSCPServer::GetMidiInstrumentMapp
2283      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2284      LSCPResultSet result;      LSCPResultSet result;
2285      try {      try {
2286          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2287          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2288          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
2289          idx.midi_prog     = MidiProg;  #if WIN32
2290            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2291    #else
2292            // assuming POSIX
2293            const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2294    #endif
2295    
2296          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2297          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          result.Add("ENGINE_NAME", entry.EngineName);
2298          if (iter == mappings.end()) result.Error("there is no map entry with that index");          result.Add("INSTRUMENT_FILE", instrumentFileName);
2299          else { // found          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2300              result.Add("NAME", iter->second.Name);          String instrumentName;
2301              result.Add("ENGINE_NAME", iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2302              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          if (pEngine) {
2303              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              if (pEngine->GetInstrumentManager()) {
2304              String instrumentName;                  InstrumentManager::instrument_id_t instrID;
2305              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);                  instrID.FileName = entry.InstrumentFile;
2306              if (pEngine) {                  instrID.Index    = entry.InstrumentIndex;
2307                  if (pEngine->GetInstrumentManager()) {                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                     InstrumentManager::instrument_id_t instrID;  
                     instrID.FileName = iter->second.InstrumentFile;  
                     instrID.Index    = iter->second.InstrumentIndex;  
                     instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);  
                 }  
                 EngineFactory::Destroy(pEngine);  
2308              }              }
2309              result.Add("INSTRUMENT_NAME", instrumentName);              EngineFactory::Destroy(pEngine);
             switch (iter->second.LoadMode) {  
                 case MidiInstrumentMapper::ON_DEMAND:  
                     result.Add("LOAD_MODE", "ON_DEMAND");  
                     break;  
                 case MidiInstrumentMapper::ON_DEMAND_HOLD:  
                     result.Add("LOAD_MODE", "ON_DEMAND_HOLD");  
                     break;  
                 case MidiInstrumentMapper::PERSISTENT:  
                     result.Add("LOAD_MODE", "PERSISTENT");  
                     break;  
                 default:  
                     throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");  
             }  
             result.Add("VOLUME", iter->second.Volume);  
2310          }          }
2311            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2312            switch (entry.LoadMode) {
2313                case MidiInstrumentMapper::ON_DEMAND:
2314                    result.Add("LOAD_MODE", "ON_DEMAND");
2315                    break;
2316                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2317                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2318                    break;
2319                case MidiInstrumentMapper::PERSISTENT:
2320                    result.Add("LOAD_MODE", "PERSISTENT");
2321                    break;
2322                default:
2323                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2324            }
2325            result.Add("VOLUME", entry.Volume);
2326      } catch (Exception e) {      } catch (Exception e) {
2327          result.Error(e);          result.Error(e);
2328      }      }
# Line 1955  String LSCPServer::GetMidiInstrumentMap( Line 2462  String LSCPServer::GetMidiInstrumentMap(
2462      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2463      LSCPResultSet result;      LSCPResultSet result;
2464      try {      try {
2465          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2466          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2467      } catch (Exception e) {      } catch (Exception e) {
2468          result.Error(e);          result.Error(e);
# Line 1986  String LSCPServer::SetChannelMap(uint ui Line 2493  String LSCPServer::SetChannelMap(uint ui
2493      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2494      LSCPResultSet result;      LSCPResultSet result;
2495      try {      try {
2496          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2497    
2498          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2499          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 2098  String LSCPServer::GetFxSendInfo(uint ui Line 2601  String LSCPServer::GetFxSendInfo(uint ui
2601              AudioRouting += ToString(pFxSend->DestinationChannel(chan));              AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2602          }          }
2603    
2604            const String sEffectRouting =
2605                (pFxSend->DestinationEffectChain() >= 0 && pFxSend->DestinationEffectChainPosition() >= 0)
2606                    ? ToString(pFxSend->DestinationEffectChain()) + "," + ToString(pFxSend->DestinationEffectChainPosition())
2607                    : "NONE";
2608    
2609          // success          // success
2610          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2611          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2612          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2613          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2614            result.Add("EFFECT", sEffectRouting);
2615      } catch (Exception e) {      } catch (Exception e) {
2616          result.Error(e);          result.Error(e);
2617      }      }
# Line 2165  String LSCPServer::SetFxSendLevel(uint u Line 2674  String LSCPServer::SetFxSendLevel(uint u
2674      return result.Produce();      return result.Produce();
2675  }  }
2676    
2677    String LSCPServer::SetFxSendEffect(uint uiSamplerChannel, uint FxSendID, int iSendEffectChain, int iEffectChainPosition) {
2678        dmsg(2,("LSCPServer: SetFxSendEffect(%d,%d)\n", iSendEffectChain, iEffectChainPosition));
2679        LSCPResultSet result;
2680        try {
2681            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2682    
2683            pFxSend->SetDestinationEffect(iSendEffectChain, iEffectChainPosition);
2684            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2685        } catch (Exception e) {
2686            result.Error(e);
2687        }
2688        return result.Produce();
2689    }
2690    
2691    String LSCPServer::GetAvailableEffects() {
2692        dmsg(2,("LSCPServer: GetAvailableEffects()\n"));
2693        LSCPResultSet result;
2694        try {
2695            int n = EffectFactory::AvailableEffectsCount();
2696            result.Add(n);
2697        }
2698        catch (Exception e) {
2699            result.Error(e);
2700        }
2701        return result.Produce();
2702    }
2703    
2704    String LSCPServer::ListAvailableEffects() {
2705        dmsg(2,("LSCPServer: ListAvailableEffects()\n"));
2706        LSCPResultSet result;
2707        String list;
2708        try {
2709            //FIXME: for now we simply enumerate from 0 .. EffectFactory::AvailableEffectsCount() here, in future we should use unique IDs for effects during the whole sampler session. This issue comes into game when the user forces a reload of available effect plugins
2710            int n = EffectFactory::AvailableEffectsCount();
2711            for (int i = 0; i < n; i++) {
2712                if (i) list += ",";
2713                list += ToString(i);
2714            }
2715        }
2716        catch (Exception e) {
2717            result.Error(e);
2718        }
2719        result.Add(list);
2720        return result.Produce();
2721    }
2722    
2723    String LSCPServer::GetEffectInfo(int iEffectIndex) {
2724        dmsg(2,("LSCPServer: GetEffectInfo(%d)\n", iEffectIndex));
2725        LSCPResultSet result;
2726        try {
2727            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2728            if (!pEffectInfo)
2729                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2730    
2731            // convert the filename into the correct encoding as defined for LSCP
2732            // (especially in terms of special characters -> escape sequences)
2733    #if WIN32
2734            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2735    #else
2736            // assuming POSIX
2737            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2738    #endif
2739    
2740            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2741            result.Add("MODULE", dllFileName);
2742            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2743            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2744        }
2745        catch (Exception e) {
2746            result.Error(e);
2747        }
2748        return result.Produce();    
2749    }
2750    
2751    String LSCPServer::GetEffectInstanceInfo(int iEffectInstance) {
2752        dmsg(2,("LSCPServer: GetEffectInstanceInfo(%d)\n", iEffectInstance));
2753        LSCPResultSet result;
2754        try {
2755            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2756            if (!pEffect)
2757                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2758    
2759            EffectInfo* pEffectInfo = pEffect->GetEffectInfo();
2760    
2761            // convert the filename into the correct encoding as defined for LSCP
2762            // (especially in terms of special characters -> escape sequences)
2763    #if WIN32
2764            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2765    #else
2766            // assuming POSIX
2767            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2768    #endif
2769    
2770            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2771            result.Add("MODULE", dllFileName);
2772            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2773            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2774            result.Add("INPUT_CONTROLS", ToString(pEffect->InputControlCount()));
2775        }
2776        catch (Exception e) {
2777            result.Error(e);
2778        }
2779        return result.Produce();
2780    }
2781    
2782    String LSCPServer::GetEffectInstanceInputControlInfo(int iEffectInstance, int iInputControlIndex) {
2783        dmsg(2,("LSCPServer: GetEffectInstanceInputControlInfo(%d,%d)\n", iEffectInstance, iInputControlIndex));
2784        LSCPResultSet result;
2785        try {
2786            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2787            if (!pEffect)
2788                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2789    
2790            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2791            if (!pEffectControl)
2792                throw Exception(
2793                    "Effect instance " + ToString(iEffectInstance) +
2794                    " does not have an input control with index " +
2795                    ToString(iInputControlIndex)
2796                );
2797    
2798            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectControl->Description()));
2799            result.Add("VALUE", pEffectControl->Value());
2800            if (pEffectControl->MinValue())
2801                 result.Add("RANGE_MIN", *pEffectControl->MinValue());
2802            if (pEffectControl->MaxValue())
2803                 result.Add("RANGE_MAX", *pEffectControl->MaxValue());
2804            if (!pEffectControl->Possibilities().empty())
2805                 result.Add("POSSIBILITIES", pEffectControl->Possibilities());
2806            if (pEffectControl->DefaultValue())
2807                 result.Add("DEFAULT", *pEffectControl->DefaultValue());
2808        } catch (Exception e) {
2809            result.Error(e);
2810        }
2811        return result.Produce();
2812    }
2813    
2814    String LSCPServer::SetEffectInstanceInputControlValue(int iEffectInstance, int iInputControlIndex, double dValue) {
2815        dmsg(2,("LSCPServer: SetEffectInstanceInputControlValue(%d,%d,%f)\n", iEffectInstance, iInputControlIndex, dValue));
2816        LSCPResultSet result;
2817        try {
2818            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2819            if (!pEffect)
2820                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2821    
2822            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2823            if (!pEffectControl)
2824                throw Exception(
2825                    "Effect instance " + ToString(iEffectInstance) +
2826                    " does not have an input control with index " +
2827                    ToString(iInputControlIndex)
2828                );
2829    
2830            pEffectControl->SetValue(dValue);
2831            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_info, iEffectInstance));
2832        } catch (Exception e) {
2833            result.Error(e);
2834        }
2835        return result.Produce();
2836    }
2837    
2838    String LSCPServer::CreateEffectInstance(int iEffectIndex) {
2839        dmsg(2,("LSCPServer: CreateEffectInstance(%d)\n", iEffectIndex));
2840        LSCPResultSet result;
2841        try {
2842            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2843            if (!pEffectInfo)
2844                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2845            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2846            result = pEffect->ID(); // success
2847            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2848        } catch (Exception e) {
2849            result.Error(e);
2850        }
2851        return result.Produce();
2852    }
2853    
2854    String LSCPServer::CreateEffectInstance(String effectSystem, String module, String effectName) {
2855        dmsg(2,("LSCPServer: CreateEffectInstance('%s','%s','%s')\n", effectSystem.c_str(), module.c_str(), effectName.c_str()));
2856        LSCPResultSet result;
2857        try {
2858            // to allow loading the same LSCP session file on different systems
2859            // successfully, probably with different effect plugin DLL paths or even
2860            // running completely different operating systems, we do the following
2861            // for finding the right effect:
2862            //
2863            // first try to search for an exact match of the effect plugin DLL
2864            // (a.k.a 'module'), to avoid picking the wrong DLL with the same
2865            // effect name ...
2866            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_MATCH_EXACTLY);
2867            // ... if no effect with exactly matchin DLL filename was found, then
2868            // try to lower the restrictions of matching the effect plugin DLL
2869            // filename and try again and again ...
2870            if (!pEffectInfo) {
2871                dmsg(2,("no exact module match, trying MODULE_IGNORE_PATH\n"));
2872                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH);
2873            }
2874            if (!pEffectInfo) {
2875                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE\n"));
2876                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE);
2877            }
2878            if (!pEffectInfo) {
2879                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE | MODULE_IGNORE_EXTENSION\n"));
2880                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE | EffectFactory::MODULE_IGNORE_EXTENSION);
2881            }
2882            // ... if there was still no effect found, then completely ignore the
2883            // DLL plugin filename argument and just search for the matching effect
2884            // system type and effect name
2885            if (!pEffectInfo) {
2886                dmsg(2,("no module match, trying MODULE_IGNORE_ALL\n"));
2887                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_ALL);
2888            }
2889            if (!pEffectInfo)
2890                throw Exception("There is no such effect '" + effectSystem + "' '" + module + "' '" + effectName + "'");
2891    
2892            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2893            result = LSCPResultSet(pEffect->ID());
2894            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2895        } catch (Exception e) {
2896            result.Error(e);
2897        }
2898        return result.Produce();
2899    }
2900    
2901    String LSCPServer::DestroyEffectInstance(int iEffectInstance) {
2902        dmsg(2,("LSCPServer: DestroyEffectInstance(%d)\n", iEffectInstance));
2903        LSCPResultSet result;
2904        try {
2905            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2906            if (!pEffect)
2907                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2908            EffectFactory::Destroy(pEffect);
2909            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2910        } catch (Exception e) {
2911            result.Error(e);
2912        }
2913        return result.Produce();
2914    }
2915    
2916    String LSCPServer::GetEffectInstances() {
2917        dmsg(2,("LSCPServer: GetEffectInstances()\n"));
2918        LSCPResultSet result;
2919        try {
2920            int n = EffectFactory::EffectInstancesCount();
2921            result.Add(n);
2922        } catch (Exception e) {
2923            result.Error(e);
2924        }
2925        return result.Produce();
2926    }
2927    
2928    String LSCPServer::ListEffectInstances() {
2929        dmsg(2,("LSCPServer: ListEffectInstances()\n"));
2930        LSCPResultSet result;
2931        String list;
2932        try {
2933            int n = EffectFactory::EffectInstancesCount();
2934            for (int i = 0; i < n; i++) {
2935                Effect* pEffect = EffectFactory::GetEffectInstance(i);
2936                if (i) list += ",";
2937                list += ToString(pEffect->ID());
2938            }
2939        } catch (Exception e) {
2940            result.Error(e);
2941        }
2942        result.Add(list);
2943        return result.Produce();
2944    }
2945    
2946    String LSCPServer::GetSendEffectChains(int iAudioOutputDevice) {
2947        dmsg(2,("LSCPServer: GetSendEffectChains(%d)\n", iAudioOutputDevice));
2948        LSCPResultSet result;
2949        try {
2950            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2951            if (!devices.count(iAudioOutputDevice))
2952                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2953            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2954            int n = pDevice->SendEffectChainCount();
2955            result.Add(n);
2956        } catch (Exception e) {
2957            result.Error(e);
2958        }
2959        return result.Produce();
2960    }
2961    
2962    String LSCPServer::ListSendEffectChains(int iAudioOutputDevice) {
2963        dmsg(2,("LSCPServer: ListSendEffectChains(%d)\n", iAudioOutputDevice));
2964        LSCPResultSet result;
2965        String list;
2966        try {
2967            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2968            if (!devices.count(iAudioOutputDevice))
2969                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2970            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2971            int n = pDevice->SendEffectChainCount();
2972            for (int i = 0; i < n; i++) {
2973                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2974                if (i) list += ",";
2975                list += ToString(pEffectChain->ID());
2976            }
2977        } catch (Exception e) {
2978            result.Error(e);
2979        }
2980        result.Add(list);
2981        return result.Produce();
2982    }
2983    
2984    String LSCPServer::AddSendEffectChain(int iAudioOutputDevice) {
2985        dmsg(2,("LSCPServer: AddSendEffectChain(%d)\n", iAudioOutputDevice));
2986        LSCPResultSet result;
2987        try {
2988            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2989            if (!devices.count(iAudioOutputDevice))
2990                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2991            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2992            EffectChain* pEffectChain = pDevice->AddSendEffectChain();
2993            result = pEffectChain->ID();
2994            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
2995        } catch (Exception e) {
2996            result.Error(e);
2997        }
2998        return result.Produce();
2999    }
3000    
3001    String LSCPServer::RemoveSendEffectChain(int iAudioOutputDevice, int iSendEffectChain) {
3002        dmsg(2,("LSCPServer: RemoveSendEffectChain(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
3003        LSCPResultSet result;
3004        try {
3005            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
3006            if (!devices.count(iAudioOutputDevice))
3007                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
3008    
3009            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
3010            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
3011            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
3012            for (; itEngineChannel != itEnd; ++itEngineChannel) {
3013                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
3014                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
3015                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
3016                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
3017                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain) {
3018                            throw Exception("The effect chain is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
3019                        }
3020                    }
3021                }
3022            }
3023    
3024            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
3025            for (int i = 0; i < pDevice->SendEffectChainCount(); i++) {
3026                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
3027                if (pEffectChain->ID() == iSendEffectChain) {
3028                    pDevice->RemoveSendEffectChain(i);
3029                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
3030                    return result.Produce();
3031                }
3032            }
3033            throw Exception(
3034                "There is no send effect chain with ID " +
3035                ToString(iSendEffectChain) + " for audio output device " +
3036                ToString(iAudioOutputDevice) + "."
3037            );
3038        } catch (Exception e) {
3039            result.Error(e);
3040        }
3041        return result.Produce();
3042    }
3043    
3044    static EffectChain* _getSendEffectChain(Sampler* pSampler, int iAudioOutputDevice, int iSendEffectChain) throw (Exception) {
3045        std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
3046        if (!devices.count(iAudioOutputDevice))
3047            throw Exception(
3048                "There is no audio output device with index " +
3049                ToString(iAudioOutputDevice) + "."
3050            );
3051        AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
3052        EffectChain* pEffectChain = pDevice->SendEffectChainByID(iSendEffectChain);
3053        if(pEffectChain != NULL) return pEffectChain;
3054        throw Exception(
3055            "There is no send effect chain with ID " +
3056            ToString(iSendEffectChain) + " for audio output device " +
3057            ToString(iAudioOutputDevice) + "."
3058        );
3059    }
3060    
3061    String LSCPServer::GetSendEffectChainInfo(int iAudioOutputDevice, int iSendEffectChain) {
3062        dmsg(2,("LSCPServer: GetSendEffectChainInfo(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
3063        LSCPResultSet result;
3064        try {
3065            EffectChain* pEffectChain =
3066                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3067            String sEffectSequence;
3068            for (int i = 0; i < pEffectChain->EffectCount(); i++) {
3069                if (i) sEffectSequence += ",";
3070                sEffectSequence += ToString(pEffectChain->GetEffect(i)->ID());
3071            }
3072            result.Add("EFFECT_COUNT", pEffectChain->EffectCount());
3073            result.Add("EFFECT_SEQUENCE", sEffectSequence);
3074        } catch (Exception e) {
3075            result.Error(e);
3076        }
3077        return result.Produce();
3078    }
3079    
3080    String LSCPServer::AppendSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectInstance) {
3081        dmsg(2,("LSCPServer: AppendSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectInstance));
3082        LSCPResultSet result;
3083        try {
3084            EffectChain* pEffectChain =
3085                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3086            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
3087            if (!pEffect)
3088                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
3089            pEffectChain->AppendEffect(pEffect);
3090            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3091        } catch (Exception e) {
3092            result.Error(e);
3093        }
3094        return result.Produce();
3095    }
3096    
3097    String LSCPServer::InsertSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition, int iEffectInstance) {
3098        dmsg(2,("LSCPServer: InsertSendEffectChainEffect(%d,%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition, iEffectInstance));
3099        LSCPResultSet result;
3100        try {
3101            EffectChain* pEffectChain =
3102                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3103            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
3104            if (!pEffect)
3105                throw Exception("There is no effect instance with index " + ToString(iEffectInstance));
3106            pEffectChain->InsertEffect(pEffect, iEffectChainPosition);
3107            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3108        } catch (Exception e) {
3109            result.Error(e);
3110        }
3111        return result.Produce();
3112    }
3113    
3114    String LSCPServer::RemoveSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition) {
3115        dmsg(2,("LSCPServer: RemoveSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition));
3116        LSCPResultSet result;
3117        try {
3118            EffectChain* pEffectChain =
3119                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3120    
3121            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
3122            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
3123            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
3124            for (; itEngineChannel != itEnd; ++itEngineChannel) {
3125                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
3126                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
3127                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
3128                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
3129                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain && fxs->DestinationEffectChainPosition() == iEffectChainPosition) {
3130                            throw Exception("The effect instance is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
3131                        }
3132                    }
3133                }
3134            }
3135    
3136            pEffectChain->RemoveEffect(iEffectChainPosition);
3137            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3138        } catch (Exception e) {
3139            result.Error(e);
3140        }
3141        return result.Produce();
3142    }
3143    
3144  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
3145      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
3146      LSCPResultSet result;      LSCPResultSet result;
3147      try {      try {
3148          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
3149          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
3150          Engine* pEngine = pEngineChannel->GetEngine();          Engine* pEngine = pEngineChannel->GetEngine();
3151          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
# Line 2187  String LSCPServer::EditSamplerChannelIns Line 3160  String LSCPServer::EditSamplerChannelIns
3160      return result.Produce();      return result.Produce();
3161  }  }
3162    
3163    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
3164        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
3165        LSCPResultSet result;
3166        try {
3167            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
3168    
3169            if (Arg1 > 127 || Arg2 > 127) {
3170                throw Exception("Invalid MIDI message");
3171            }
3172    
3173            VirtualMidiDevice* pMidiDevice = NULL;
3174            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
3175            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
3176                if ((*iter).pEngineChannel == pEngineChannel) {
3177                    pMidiDevice = (*iter).pMidiListener;
3178                    break;
3179                }
3180            }
3181            
3182            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
3183    
3184            if (MidiMsg == "NOTE_ON") {
3185                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
3186                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
3187                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3188            } else if (MidiMsg == "NOTE_OFF") {
3189                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
3190                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
3191                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3192            } else if (MidiMsg == "CC") {
3193                pMidiDevice->SendCCToDevice(Arg1, Arg2);
3194                bool b = pMidiDevice->SendCCToSampler(Arg1, Arg2);
3195                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3196            } else {
3197                throw Exception("Unknown MIDI message type: " + MidiMsg);
3198            }
3199        } catch (Exception e) {
3200            result.Error(e);
3201        }
3202        return result.Produce();
3203    }
3204    
3205  /**  /**
3206   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
3207   */   */
# Line 2194  String LSCPServer::ResetChannel(uint uiS Line 3209  String LSCPServer::ResetChannel(uint uiS
3209      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
3210      LSCPResultSet result;      LSCPResultSet result;
3211      try {      try {
3212          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
3213          pEngineChannel->Reset();          pEngineChannel->Reset();
3214      }      }
3215      catch (Exception e) {      catch (Exception e) {
# Line 2222  String LSCPServer::ResetSampler() { Line 3234  String LSCPServer::ResetSampler() {
3234   */   */
3235  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
3236      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
3237        const std::string description =
3238            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
3239      LSCPResultSet result;      LSCPResultSet result;
3240      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
3241      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
3242      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
3243  #if HAVE_SQLITE3  #if HAVE_SQLITE3
# Line 2236  String LSCPServer::GetServerInfo() { Line 3250  String LSCPServer::GetServerInfo() {
3250  }  }
3251    
3252  /**  /**
3253     * Will be called by the parser to return the current number of all active streams.
3254     */
3255    String LSCPServer::GetTotalStreamCount() {
3256        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
3257        LSCPResultSet result;
3258        result.Add(pSampler->GetDiskStreamCount());
3259        return result.Produce();
3260    }
3261    
3262    /**
3263   * Will be called by the parser to return the current number of all active voices.   * Will be called by the parser to return the current number of all active voices.
3264   */   */
3265  String LSCPServer::GetTotalVoiceCount() {  String LSCPServer::GetTotalVoiceCount() {
# Line 2251  String LSCPServer::GetTotalVoiceCount() Line 3275  String LSCPServer::GetTotalVoiceCount()
3275  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
3276      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
3277      LSCPResultSet result;      LSCPResultSet result;
3278      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * pSampler->GetGlobalMaxVoices());
3279        return result.Produce();
3280    }
3281    
3282    /**
3283     * Will be called by the parser to return the sampler global maximum
3284     * allowed number of voices.
3285     */
3286    String LSCPServer::GetGlobalMaxVoices() {
3287        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
3288        LSCPResultSet result;
3289        result.Add(pSampler->GetGlobalMaxVoices());
3290        return result.Produce();
3291    }
3292    
3293    /**
3294     * Will be called by the parser to set the sampler global maximum number of
3295     * voices.
3296     */
3297    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
3298        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
3299        LSCPResultSet result;
3300        try {
3301            pSampler->SetGlobalMaxVoices(iVoices);
3302            LSCPServer::SendLSCPNotify(
3303                LSCPEvent(LSCPEvent::event_global_info, "VOICES", pSampler->GetGlobalMaxVoices())
3304            );
3305        } catch (Exception e) {
3306            result.Error(e);
3307        }
3308        return result.Produce();
3309    }
3310    
3311    /**
3312     * Will be called by the parser to return the sampler global maximum
3313     * allowed number of disk streams.
3314     */
3315    String LSCPServer::GetGlobalMaxStreams() {
3316        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
3317        LSCPResultSet result;
3318        result.Add(pSampler->GetGlobalMaxStreams());
3319        return result.Produce();
3320    }
3321    
3322    /**
3323     * Will be called by the parser to set the sampler global maximum number of
3324     * disk streams.
3325     */
3326    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
3327        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
3328        LSCPResultSet result;
3329        try {
3330            pSampler->SetGlobalMaxStreams(iStreams);
3331            LSCPServer::SendLSCPNotify(
3332                LSCPEvent(LSCPEvent::event_global_info, "STREAMS", pSampler->GetGlobalMaxStreams())
3333            );
3334        } catch (Exception e) {
3335            result.Error(e);
3336        }
3337      return result.Produce();      return result.Produce();
3338  }  }
3339    
# Line 2265  String LSCPServer::SetGlobalVolume(doubl Line 3347  String LSCPServer::SetGlobalVolume(doubl
3347      LSCPResultSet result;      LSCPResultSet result;
3348      try {      try {
3349          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
3350          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
3351          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
3352      } catch (Exception e) {      } catch (Exception e) {
3353          result.Error(e);          result.Error(e);
# Line 2273  String LSCPServer::SetGlobalVolume(doubl Line 3355  String LSCPServer::SetGlobalVolume(doubl
3355      return result.Produce();      return result.Produce();
3356  }  }
3357    
3358    String LSCPServer::GetFileInstruments(String Filename) {
3359        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
3360        LSCPResultSet result;
3361        try {
3362            VerifyFile(Filename);
3363        } catch (Exception e) {
3364            result.Error(e);
3365            return result.Produce();
3366        }
3367        // try to find a sampler engine that can handle the file
3368        bool bFound = false;
3369        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
3370        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
3371            Engine* pEngine = NULL;
3372            try {
3373                pEngine = EngineFactory::Create(engineTypes[i]);
3374                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
3375                InstrumentManager* pManager = pEngine->GetInstrumentManager();
3376                if (pManager) {
3377                    std::vector<InstrumentManager::instrument_id_t> IDs =
3378                        pManager->GetInstrumentFileContent(Filename);
3379                    // return the amount of instruments in the file
3380                    result.Add(IDs.size());
3381                    // no more need to ask other engine types
3382                    bFound = true;
3383                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
3384            } catch (Exception e) {
3385                // NOOP, as exception is thrown if engine doesn't support file
3386            }
3387            if (pEngine) EngineFactory::Destroy(pEngine);
3388        }
3389    
3390        if (!bFound) result.Error("Unknown file format");
3391        return result.Produce();
3392    }
3393    
3394    String LSCPServer::ListFileInstruments(String Filename) {
3395        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
3396        LSCPResultSet result;
3397        try {
3398            VerifyFile(Filename);
3399        } catch (Exception e) {
3400            result.Error(e);
3401            return result.Produce();
3402        }
3403        // try to find a sampler engine that can handle the file
3404        bool bFound = false;
3405        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
3406        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
3407            Engine* pEngine = NULL;
3408            try {
3409                pEngine = EngineFactory::Create(engineTypes[i]);
3410                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
3411                InstrumentManager* pManager = pEngine->GetInstrumentManager();
3412                if (pManager) {
3413                    std::vector<InstrumentManager::instrument_id_t> IDs =
3414                        pManager->GetInstrumentFileContent(Filename);
3415                    // return a list of IDs of the instruments in the file
3416                    String s;
3417                    for (int j = 0; j < IDs.size(); j++) {
3418                        if (s.size()) s += ",";
3419                        s += ToString(IDs[j].Index);
3420                    }
3421                    result.Add(s);
3422                    // no more need to ask other engine types
3423                    bFound = true;
3424                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
3425            } catch (Exception e) {
3426                // NOOP, as exception is thrown if engine doesn't support file
3427            }
3428            if (pEngine) EngineFactory::Destroy(pEngine);
3429        }
3430    
3431        if (!bFound) result.Error("Unknown file format");
3432        return result.Produce();
3433    }
3434    
3435    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
3436        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
3437        LSCPResultSet result;
3438        try {
3439            VerifyFile(Filename);
3440        } catch (Exception e) {
3441            result.Error(e);
3442            return result.Produce();
3443        }
3444        InstrumentManager::instrument_id_t id;
3445        id.FileName = Filename;
3446        id.Index    = InstrumentID;
3447        // try to find a sampler engine that can handle the file
3448        bool bFound = false;
3449        bool bFatalErr = false;
3450        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
3451        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
3452            Engine* pEngine = NULL;
3453            try {
3454                pEngine = EngineFactory::Create(engineTypes[i]);
3455                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
3456                InstrumentManager* pManager = pEngine->GetInstrumentManager();
3457                if (pManager) {
3458                    // check if the instrument index is valid
3459                    // FIXME: this won't work if an engine only supports parts of the instrument file
3460                    std::vector<InstrumentManager::instrument_id_t> IDs =
3461                        pManager->GetInstrumentFileContent(Filename);
3462                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
3463                        std::stringstream ss;
3464                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
3465                        bFatalErr = true;
3466                        throw Exception(ss.str());
3467                    }
3468                    // get the info of the requested instrument
3469                    InstrumentManager::instrument_info_t info =
3470                        pManager->GetInstrumentInfo(id);
3471                    // return detailed informations about the file
3472                    result.Add("NAME", info.InstrumentName);
3473                    result.Add("FORMAT_FAMILY", engineTypes[i]);
3474                    result.Add("FORMAT_VERSION", info.FormatVersion);
3475                    result.Add("PRODUCT", info.Product);
3476                    result.Add("ARTISTS", info.Artists);
3477    
3478                    std::stringstream ss;
3479                    bool b = false;
3480                    for (int i = 0; i < 128; i++) {
3481                        if (info.KeyBindings[i]) {
3482                            if (b) ss << ',';
3483                            ss << i; b = true;
3484                        }
3485                    }
3486                    result.Add("KEY_BINDINGS", ss.str());
3487    
3488                    b = false;
3489                    std::stringstream ss2;
3490                    for (int i = 0; i < 128; i++) {
3491                        if (info.KeySwitchBindings[i]) {
3492                            if (b) ss2 << ',';
3493                            ss2 << i; b = true;
3494                        }
3495                    }
3496                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
3497                    // no more need to ask other engine types
3498                    bFound = true;
3499                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
3500            } catch (Exception e) {
3501                // usually NOOP, as exception is thrown if engine doesn't support file
3502                if (bFatalErr) result.Error(e);
3503            }
3504            if (pEngine) EngineFactory::Destroy(pEngine);
3505        }
3506    
3507        if (!bFound && !bFatalErr) result.Error("Unknown file format");
3508        return result.Produce();
3509    }
3510    
3511    void LSCPServer::VerifyFile(String Filename) {
3512        #if WIN32
3513        WIN32_FIND_DATA win32FileAttributeData;
3514        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
3515        if (!res) {
3516            std::stringstream ss;
3517            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
3518            throw Exception(ss.str());
3519        }
3520        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
3521            throw Exception("Directory is specified");
3522        }
3523        #else
3524        File f(Filename);
3525        if(!f.Exist()) throw Exception(f.GetErrorMsg());
3526        if (f.IsDirectory()) throw Exception("Directory is specified");
3527        #endif
3528    }
3529    
3530  /**  /**
3531   * 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
3532   * server for receiving event messages.   * server for receiving event messages.
# Line 2280  String LSCPServer::SetGlobalVolume(doubl Line 3534  String LSCPServer::SetGlobalVolume(doubl
3534  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
3535      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3536      LSCPResultSet result;      LSCPResultSet result;
3537      SubscriptionMutex.Lock();      {
3538      eventSubscriptions[type].push_back(currentSocket);          LockGuard lock(SubscriptionMutex);
3539      SubscriptionMutex.Unlock();          eventSubscriptions[type].push_back(currentSocket);
3540        }
3541      return result.Produce();      return result.Produce();
3542  }  }
3543    
# Line 2293  String LSCPServer::SubscribeNotification Line 3548  String LSCPServer::SubscribeNotification
3548  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
3549      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3550      LSCPResultSet result;      LSCPResultSet result;
3551      SubscriptionMutex.Lock();      {
3552      eventSubscriptions[type].remove(currentSocket);          LockGuard lock(SubscriptionMutex);
3553      SubscriptionMutex.Unlock();          eventSubscriptions[type].remove(currentSocket);
3554        }
3555      return result.Produce();      return result.Produce();
3556  }  }
3557    
# Line 2374  String LSCPServer::GetDbInstrumentDirect Line 3630  String LSCPServer::GetDbInstrumentDirect
3630      try {      try {
3631          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
3632    
3633          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3634          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
3635          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
3636      } catch (Exception e) {      } catch (Exception e) {
# Line 2464  String LSCPServer::AddDbInstruments(Stri Line 3720  String LSCPServer::AddDbInstruments(Stri
3720      return result.Produce();      return result.Produce();
3721  }  }
3722    
3723  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3724      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
3725      LSCPResultSet result;      LSCPResultSet result;
3726  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3727      try {      try {
3728          int id;          int id;
3729          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3730          if (ScanMode.compare("RECURSIVE") == 0) {          if (ScanMode.compare("RECURSIVE") == 0) {
3731             id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3732          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3733             id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3734          } else if (ScanMode.compare("FLAT") == 0) {          } else if (ScanMode.compare("FLAT") == 0) {
3735             id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);              id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3736          } else {          } else {
3737              throw Exception("Unknown scan mode: " + ScanMode);              throw Exception("Unknown scan mode: " + ScanMode);
3738          }          }
# Line 2558  String LSCPServer::GetDbInstrumentInfo(S Line 3814  String LSCPServer::GetDbInstrumentInfo(S
3814          result.Add("SIZE", (int)info.Size);          result.Add("SIZE", (int)info.Size);
3815          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
3816          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
3817          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3818          result.Add("IS_DRUM", info.IsDrum);          result.Add("IS_DRUM", info.IsDrum);
3819          result.Add("PRODUCT", InstrumentsDb::toEscapedText(info.Product));          result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3820          result.Add("ARTISTS", InstrumentsDb::toEscapedText(info.Artists));          result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3821          result.Add("KEYWORDS", InstrumentsDb::toEscapedText(info.Keywords));          result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3822      } catch (Exception e) {      } catch (Exception e) {
3823           result.Error(e);           result.Error(e);
3824      }      }
# Line 2652  String LSCPServer::SetDbInstrumentDescri Line 3908  String LSCPServer::SetDbInstrumentDescri
3908      return result.Produce();      return result.Produce();
3909  }  }
3910    
3911    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3912        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3913        LSCPResultSet result;
3914    #if HAVE_SQLITE3
3915        try {
3916            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3917        } catch (Exception e) {
3918             result.Error(e);
3919        }
3920    #else
3921        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3922    #endif
3923        return result.Produce();
3924    }
3925    
3926    String LSCPServer::FindLostDbInstrumentFiles() {
3927        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3928        LSCPResultSet result;
3929    #if HAVE_SQLITE3
3930        try {
3931            String list;
3932            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3933    
3934            for (int i = 0; i < pLostFiles->size(); i++) {
3935                if (list != "") list += ",";
3936                list += "'" + pLostFiles->at(i) + "'";
3937            }
3938    
3939            result.Add(list);
3940        } catch (Exception e) {
3941             result.Error(e);
3942        }
3943    #else
3944        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3945    #endif
3946        return result.Produce();
3947    }
3948    
3949  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3950      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3951      LSCPResultSet result;      LSCPResultSet result;
# Line 2748  String LSCPServer::FindDbInstruments(Str Line 4042  String LSCPServer::FindDbInstruments(Str
4042      return result.Produce();      return result.Produce();
4043  }  }
4044    
4045    String LSCPServer::FormatInstrumentsDb() {
4046        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
4047        LSCPResultSet result;
4048    #if HAVE_SQLITE3
4049        try {
4050            InstrumentsDb::GetInstrumentsDb()->Format();
4051        } catch (Exception e) {
4052             result.Error(e);
4053        }
4054    #else
4055        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
4056    #endif
4057        return result.Produce();
4058    }
4059    
4060    
4061  /**  /**
4062   * Will be called by the parser to enable or disable echo mode; if echo   * Will be called by the parser to enable or disable echo mode; if echo
# Line 2767  String LSCPServer::SetEcho(yyparse_param Line 4076  String LSCPServer::SetEcho(yyparse_param
4076      }      }
4077      return result.Produce();      return result.Produce();
4078  }  }
4079    
4080    String LSCPServer::SetShellInteract(yyparse_param_t* pSession, double boolean_value) {
4081        dmsg(2,("LSCPServer: SetShellInteract(val=%f)\n", boolean_value));
4082        LSCPResultSet result;
4083        try {
4084            if      (boolean_value == 0) pSession->bShellInteract = false;
4085            else if (boolean_value == 1) pSession->bShellInteract = true;
4086            else throw Exception("Not a boolean value, must either be 0 or 1");
4087        } catch (Exception e) {
4088            result.Error(e);
4089        }
4090        return result.Produce();
4091    }
4092    
4093    String LSCPServer::SetShellAutoCorrect(yyparse_param_t* pSession, double boolean_value) {
4094        dmsg(2,("LSCPServer: SetShellAutoCorrect(val=%f)\n", boolean_value));
4095        LSCPResultSet result;
4096        try {
4097            if      (boolean_value == 0) pSession->bShellAutoCorrect = false;
4098            else if (boolean_value == 1) pSession->bShellAutoCorrect = true;
4099            else throw Exception("Not a boolean value, must either be 0 or 1");
4100        } catch (Exception e) {
4101            result.Error(e);
4102        }
4103        return result.Produce();
4104    }
4105    
4106    String LSCPServer::SetShellDoc(yyparse_param_t* pSession, double boolean_value) {
4107        dmsg(2,("LSCPServer: SetShellDoc(val=%f)\n", boolean_value));
4108        LSCPResultSet result;
4109        try {
4110            if      (boolean_value == 0) pSession->bShellSendLSCPDoc = false;
4111            else if (boolean_value == 1) pSession->bShellSendLSCPDoc = true;
4112            else throw Exception("Not a boolean value, must either be 0 or 1");
4113        } catch (Exception e) {
4114            result.Error(e);
4115        }
4116        return result.Produce();
4117    }
4118    
4119    }

Legend:
Removed from v.1350  
changed lines
  Added in v.2535

  ViewVC Help
Powered by ViewVC