/[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 1200 by iliev, Thu May 24 14:04:18 2007 UTC revision 1835 by iliev, Mon Feb 16 17:56:50 2009 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2008 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 36  Line 44 
44  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
45  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
46    
47    namespace LinuxSampler {
48    
49    /**
50     * Returns a copy of the given string where all special characters are
51     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
52     * to escape LSCP response fields in case the respective response field is
53     * actually defined as using escape sequences in the LSCP specs.
54     *
55     * @e Caution: DO NOT use this function for escaping path based responses,
56     * use the Path class (src/common/Path.h) for this instead!
57     */
58    static String _escapeLscpResponse(String txt) {
59        for (int i = 0; i < txt.length(); i++) {
60            const char c = txt.c_str()[i];
61            if (
62                !(c >= '0' && c <= '9') &&
63                !(c >= 'a' && c <= 'z') &&
64                !(c >= 'A' && c <= 'Z') &&
65                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
66                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
67                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
68                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
69                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
70                !(c == '@') && !(c == '[') && !(c == ']') &&
71                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
72                !(c == '|') && !(c == '}') && !(c == '~')
73            ) {
74                // convert the "special" character into a "\xHH" LSCP escape sequence
75                char buf[5];
76                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
77                txt.replace(i, 1, buf);
78                i += 3;
79            }
80        }
81        return txt;
82    }
83    
84  /**  /**
85   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
86   * The big assumption here is that LSCPServer is going to remain a singleton.   * The big assumption here is that LSCPServer is going to remain a singleton.
# Line 52  Line 97 
97  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
98  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
99  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
100    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
101  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
102  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
103  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
# Line 60  Mutex LSCPServer::NotifyBufferMutex = Mu Line 106  Mutex LSCPServer::NotifyBufferMutex = Mu
106  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
107  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
108    
109  LSCPServer::LSCPServer(Sampler* pSampler, 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) {
110      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
111      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
112      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 86  LSCPServer::LSCPServer(Sampler* pSampler Line 132  LSCPServer::LSCPServer(Sampler* pSampler
132      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
133      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
134      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
135        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
136      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
137      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
138        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
139        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
140      hSocket = -1;      hSocket = -1;
141  }  }
142    
143  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
144    #if defined(WIN32)
145        if (hSocket >= 0) closesocket(hSocket);
146    #else
147      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
148    #endif
149    }
150    
151    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
152        this->pParent = pParent;
153    }
154    
155    LSCPServer::EventHandler::~EventHandler() {
156        std::vector<midi_listener_entry> l = channelMidiListeners;
157        channelMidiListeners.clear();
158        for (int i = 0; i < l.size(); i++)
159            delete l[i].pMidiListener;
160  }  }
161    
162  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
163      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
164  }  }
165    
166    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
167        pChannel->AddEngineChangeListener(this);
168    }
169    
170    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
171        if (!pChannel->GetEngineChannel()) return;
172        EngineToBeChanged(pChannel->Index());
173    }
174    
175    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
176        SamplerChannel* pSamplerChannel =
177            pParent->pSampler->GetSamplerChannel(ChannelId);
178        if (!pSamplerChannel) return;
179        EngineChannel* pEngineChannel =
180            pSamplerChannel->GetEngineChannel();
181        if (!pEngineChannel) return;
182        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
183            if ((*iter).pEngineChannel == pEngineChannel) {
184                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
185                pEngineChannel->Disconnect(pMidiListener);
186                channelMidiListeners.erase(iter);
187                delete pMidiListener;
188                return;
189            }
190        }
191    }
192    
193    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
194        SamplerChannel* pSamplerChannel =
195            pParent->pSampler->GetSamplerChannel(ChannelId);
196        if (!pSamplerChannel) return;
197        EngineChannel* pEngineChannel =
198            pSamplerChannel->GetEngineChannel();
199        if (!pEngineChannel) return;
200        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
201        pEngineChannel->Connect(pMidiListener);
202        midi_listener_entry entry = {
203            pSamplerChannel, pEngineChannel, pMidiListener
204        };
205        channelMidiListeners.push_back(entry);
206    }
207    
208  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
209      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
210  }  }
# Line 107  void LSCPServer::EventHandler::MidiDevic Line 213  void LSCPServer::EventHandler::MidiDevic
213      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
214  }  }
215    
216    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
217        pDevice->RemoveMidiPortCountListener(this);
218        for (int i = 0; i < pDevice->PortCount(); ++i)
219            MidiPortToBeRemoved(pDevice->GetPort(i));
220    }
221    
222    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
223        pDevice->AddMidiPortCountListener(this);
224        for (int i = 0; i < pDevice->PortCount(); ++i)
225            MidiPortAdded(pDevice->GetPort(i));
226    }
227    
228    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
229        // yet unused
230    }
231    
232    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
233        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
234            if ((*iter).pPort == pPort) {
235                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
236                pPort->Disconnect(pMidiListener);
237                deviceMidiListeners.erase(iter);
238                delete pMidiListener;
239                return;
240            }
241        }
242    }
243    
244    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
245        // find out the device ID
246        std::map<uint, MidiInputDevice*> devices =
247            pParent->pSampler->GetMidiInputDevices();
248        for (
249            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
250            iter != devices.end(); ++iter
251        ) {
252            if (iter->second == pPort->GetDevice()) { // found
253                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
254                pPort->Connect(pMidiListener);
255                device_midi_listener_entry entry = {
256                    pPort, pMidiListener, iter->first
257                };
258                deviceMidiListeners.push_back(entry);
259                return;
260            }
261        }
262    }
263    
264  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
265      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
266  }  }
# Line 143  void LSCPServer::EventHandler::TotalVoic Line 297  void LSCPServer::EventHandler::TotalVoic
297      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
298  }  }
299    
300    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
301        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
302    }
303    
304  #if HAVE_SQLITE3  #if HAVE_SQLITE3
305  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
306      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
307  }  }
308    
309  void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
310      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
311  }  }
312    
313  void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
314      Dir = "'" + Dir + "'";      Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
315      NewName = "'" + NewName + "'";      NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
316      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
317  }  }
318    
319  void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
320      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
321  }  }
322    
323  void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
324      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, Instr));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
325  }  }
326    
327  void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
328      Instr = "'" + Instr + "'";      Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
329      NewName = "'" + NewName + "'";      NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
330      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
331  }  }
332    
# Line 177  void LSCPServer::DbInstrumentsEventHandl Line 335  void LSCPServer::DbInstrumentsEventHandl
335  }  }
336  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
337    
338    void LSCPServer::RemoveListeners() {
339        pSampler->RemoveChannelCountListener(&eventHandler);
340        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
341        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
342        pSampler->RemoveVoiceCountListener(&eventHandler);
343        pSampler->RemoveStreamCountListener(&eventHandler);
344        pSampler->RemoveBufferFillListener(&eventHandler);
345        pSampler->RemoveTotalStreamCountListener(&eventHandler);
346        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
347        pSampler->RemoveFxSendCountListener(&eventHandler);
348        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
349        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
350        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
351        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
352    #if HAVE_SQLITE3
353        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
354    #endif
355    }
356    
357  /**  /**
358   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 193  int LSCPServer::WaitUntilInitialized(lon Line 369  int LSCPServer::WaitUntilInitialized(lon
369  }  }
370    
371  int LSCPServer::Main() {  int LSCPServer::Main() {
372            #if defined(WIN32)
373            WSADATA wsaData;
374            int iResult;
375            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
376            if (iResult != 0) {
377                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
378                    exit(EXIT_FAILURE);
379            }
380            #endif
381      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
382      if (hSocket < 0) {      if (hSocket < 0) {
383          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 206  int LSCPServer::Main() { Line 391  int LSCPServer::Main() {
391              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
392                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
393                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
394                        #if defined(WIN32)
395                        closesocket(hSocket);
396                        #else
397                      close(hSocket);                      close(hSocket);
398                        #endif
399                      //return -1;                      //return -1;
400                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
401                  }                  }
# Line 218  int LSCPServer::Main() { Line 407  int LSCPServer::Main() {
407    
408      listen(hSocket, 1);      listen(hSocket, 1);
409      Initialized.Set(true);      Initialized.Set(true);
410        
411      // Registering event listeners      // Registering event listeners
412      pSampler->AddChannelCountListener(&eventHandler);      pSampler->AddChannelCountListener(&eventHandler);
413      pSampler->AddAudioDeviceCountListener(&eventHandler);      pSampler->AddAudioDeviceCountListener(&eventHandler);
# Line 226  int LSCPServer::Main() { Line 415  int LSCPServer::Main() {
415      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
416      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
417      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
418        pSampler->AddTotalStreamCountListener(&eventHandler);
419      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
420      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
421      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
# Line 245  int LSCPServer::Main() { Line 435  int LSCPServer::Main() {
435      timeval timeout;      timeval timeout;
436    
437      while (true) {      while (true) {
438            #if CONFIG_PTHREAD_TESTCANCEL
439                    TestCancel();
440            #endif
441          // 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
442          {          {
443              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 252  int LSCPServer::Main() { Line 445  int LSCPServer::Main() {
445              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
446              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
447                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
448                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
449                  }                  }
450    
451                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
452                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
453                      if(fxs != NULL && fxs->IsInfoChanged()) {                      if(fxs != NULL && fxs->IsInfoChanged()) {
454                          int chn = (*itEngineChannel)->iSamplerChannelIndex;                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
455                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
456                          fxs->SetInfoChanged(false);                          fxs->SetInfoChanged(false);
457                      }                      }
# Line 266  int LSCPServer::Main() { Line 459  int LSCPServer::Main() {
459              }              }
460          }          }
461    
462            // check if MIDI data arrived on some engine channel
463            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
464                const EventHandler::midi_listener_entry entry =
465                    eventHandler.channelMidiListeners[i];
466                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
467                if (pMidiListener->NotesChanged()) {
468                    for (int iNote = 0; iNote < 128; iNote++) {
469                        if (pMidiListener->NoteChanged(iNote)) {
470                            const bool bActive = pMidiListener->NoteIsActive(iNote);
471                            LSCPServer::SendLSCPNotify(
472                                LSCPEvent(
473                                    LSCPEvent::event_channel_midi,
474                                    entry.pSamplerChannel->Index(),
475                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
476                                    iNote,
477                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
478                                            : pMidiListener->NoteOffVelocity(iNote)
479                                )
480                            );
481                        }
482                    }
483                }
484            }
485    
486            // check if MIDI data arrived on some MIDI device
487            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
488                const EventHandler::device_midi_listener_entry entry =
489                    eventHandler.deviceMidiListeners[i];
490                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
491                if (pMidiListener->NotesChanged()) {
492                    for (int iNote = 0; iNote < 128; iNote++) {
493                        if (pMidiListener->NoteChanged(iNote)) {
494                            const bool bActive = pMidiListener->NoteIsActive(iNote);
495                            LSCPServer::SendLSCPNotify(
496                                LSCPEvent(
497                                    LSCPEvent::event_device_midi,
498                                    entry.uiDeviceID,
499                                    entry.pPort->GetPortNumber(),
500                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
501                                    iNote,
502                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
503                                            : pMidiListener->NoteOffVelocity(iNote)
504                                )
505                            );
506                        }
507                    }
508                }
509            }
510    
511          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
512          NotifyBufferMutex.Lock();          NotifyBufferMutex.Lock();
513          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
# Line 284  int LSCPServer::Main() { Line 526  int LSCPServer::Main() {
526    
527          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
528    
529          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
530                  continue; //Nothing try again                  continue; //Nothing try again
531          if (retval == -1) {          if (retval == -1) {
532                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
533                    #if defined(WIN32)
534                    closesocket(hSocket);
535                    #else
536                  close(hSocket);                  close(hSocket);
537                    #endif
538                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
539          }          }
540    
# Line 300  int LSCPServer::Main() { Line 546  int LSCPServer::Main() {
546                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
547                  }                  }
548    
549                    #if defined(WIN32)
550                    u_long nonblock_io = 1;
551                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
552                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
553                      exit(EXIT_FAILURE);
554                    }
555            #else
556                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
557                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
558                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
559                  }                  }
560                    #endif
561    
562                  // Parser initialization                  // Parser initialization
563                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 327  int LSCPServer::Main() { Line 581  int LSCPServer::Main() {
581                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
582                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
583                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
584                                    itCurrentSession = iter; // another hack
585                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
586                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
587                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
588                                  }                                  }
589                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
590                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
591                                    itCurrentSession = Sessions.end(); // hack as well
592                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
593                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
594                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 360  void LSCPServer::CloseConnection( std::v Line 616  void LSCPServer::CloseConnection( std::v
616          NotifyMutex.Lock();          NotifyMutex.Lock();
617          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
618          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
619            #if defined(WIN32)
620            closesocket(socket);
621            #else
622          close(socket);          close(socket);
623            #endif
624          NotifyMutex.Unlock();          NotifyMutex.Unlock();
625  }  }
626    
627    void LSCPServer::LockRTNotify() {
628        RTNotifyMutex.Lock();
629    }
630    
631    void LSCPServer::UnlockRTNotify() {
632        RTNotifyMutex.Unlock();
633    }
634    
635  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
636          int subs = 0;          int subs = 0;
637          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 425  extern int GetLSCPCommand( void *buf, in Line 693  extern int GetLSCPCommand( void *buf, in
693          return command.size();          return command.size();
694  }  }
695    
696    extern yyparse_param_t* GetCurrentYaccSession() {
697        return &(*itCurrentSession);
698    }
699    
700  /**  /**
701   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
702   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
# Line 435  bool LSCPServer::GetLSCPCommand( std::ve Line 707  bool LSCPServer::GetLSCPCommand( std::ve
707          char c;          char c;
708          int i = 0;          int i = 0;
709          while (true) {          while (true) {
710                    #if defined(WIN32)
711                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
712                    #else
713                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
714                    #endif
715                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection
716                          CloseConnection(iter);                          CloseConnection(iter);
717                          break;                          break;
# Line 450  bool LSCPServer::GetLSCPCommand( std::ve Line 726  bool LSCPServer::GetLSCPCommand( std::ve
726                          }                          }
727                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
728                  }                  }
729                    #if defined(WIN32)
730                    if (result == SOCKET_ERROR) {
731                        int wsa_lasterror = WSAGetLastError();
732                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
733                                    return false;
734                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
735                            CloseConnection(iter);
736                            break;
737                    }
738                    #else
739                  if (result == -1) {                  if (result == -1) {
740                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
741                                  return false;                                  return false;
# Line 488  bool LSCPServer::GetLSCPCommand( std::ve Line 774  bool LSCPServer::GetLSCPCommand( std::ve
774                          CloseConnection(iter);                          CloseConnection(iter);
775                          break;                          break;
776                  }                  }
777                    #endif
778          }          }
779          return false;          return false;
780  }  }
# Line 612  EngineChannel* LSCPServer::GetEngineChan Line 899  EngineChannel* LSCPServer::GetEngineChan
899      EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();      EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
900      if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");      if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
901    
902      return pEngineChannel;              return pEngineChannel;
903  }  }
904    
905  /**  /**
# Line 761  String LSCPServer::GetEngineInfo(String Line 1048  String LSCPServer::GetEngineInfo(String
1048      LockRTNotify();      LockRTNotify();
1049      try {      try {
1050          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1051          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1052          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1053          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1054      }      }
# Line 834  String LSCPServer::GetChannelInfo(uint u Line 1121  String LSCPServer::GetChannelInfo(uint u
1121          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1122          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1123    
1124            // convert the filename into the correct encoding as defined for LSCP
1125            // (especially in terms of special characters -> escape sequences)
1126            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1127    #if WIN32
1128                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1129    #else
1130                // assuming POSIX
1131                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1132    #endif
1133            }
1134    
1135          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1136          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1137          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1138          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1139          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1140          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 856  String LSCPServer::GetVoiceCount(uint ui Line 1154  String LSCPServer::GetVoiceCount(uint ui
1154      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1155      LSCPResultSet result;      LSCPResultSet result;
1156      try {      try {
1157          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");  
1158          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");
1159          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1160      }      }
# Line 877  String LSCPServer::GetStreamCount(uint u Line 1172  String LSCPServer::GetStreamCount(uint u
1172      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1173      LSCPResultSet result;      LSCPResultSet result;
1174      try {      try {
1175          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");  
1176          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");
1177          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1178      }      }
# Line 898  String LSCPServer::GetBufferFill(fill_re Line 1190  String LSCPServer::GetBufferFill(fill_re
1190      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1191      LSCPResultSet result;      LSCPResultSet result;
1192      try {      try {
1193          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");  
1194          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");
1195          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1196          else {          else {
# Line 989  String LSCPServer::GetMidiInputDriverInf Line 1278  String LSCPServer::GetMidiInputDriverInf
1278              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1279                  if (s != "") s += ",";                  if (s != "") s += ",";
1280                  s += iter->first;                  s += iter->first;
1281                    delete iter->second;
1282              }              }
1283              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1284          }          }
# Line 1013  String LSCPServer::GetAudioOutputDriverI Line 1303  String LSCPServer::GetAudioOutputDriverI
1303              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1304                  if (s != "") s += ",";                  if (s != "") s += ",";
1305                  s += iter->first;                  s += iter->first;
1306                    delete iter->second;
1307              }              }
1308              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1309          }          }
# Line 1043  String LSCPServer::GetMidiInputDriverPar Line 1334  String LSCPServer::GetMidiInputDriverPar
1334          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1335          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1336          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1337            delete pParameter;
1338      }      }
1339      catch (Exception e) {      catch (Exception e) {
1340          result.Error(e);          result.Error(e);
# Line 1070  String LSCPServer::GetAudioOutputDriverP Line 1362  String LSCPServer::GetAudioOutputDriverP
1362          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1363          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1364          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1365            delete pParameter;
1366      }      }
1367      catch (Exception e) {      catch (Exception e) {
1368          result.Error(e);          result.Error(e);
# Line 1579  String LSCPServer::SetVolume(double dVol Line 1872  String LSCPServer::SetVolume(double dVol
1872      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1873      LSCPResultSet result;      LSCPResultSet result;
1874      try {      try {
1875          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");  
1876          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
1877      }      }
1878      catch (Exception e) {      catch (Exception e) {
# Line 1598  String LSCPServer::SetChannelMute(bool b Line 1888  String LSCPServer::SetChannelMute(bool b
1888      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1889      LSCPResultSet result;      LSCPResultSet result;
1890      try {      try {
1891          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");  
1892    
1893          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1894          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1619  String LSCPServer::SetChannelSolo(bool b Line 1905  String LSCPServer::SetChannelSolo(bool b
1905      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1906      LSCPResultSet result;      LSCPResultSet result;
1907      try {      try {
1908          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");  
1909    
1910          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1911          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
# Line 1743  String LSCPServer::GetMidiInstrumentMapp Line 2025  String LSCPServer::GetMidiInstrumentMapp
2025      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2026      LSCPResultSet result;      LSCPResultSet result;
2027      try {      try {
2028          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2029      } catch (Exception e) {      } catch (Exception e) {
2030          result.Error(e);          result.Error(e);
2031      }      }
# Line 1754  String LSCPServer::GetMidiInstrumentMapp Line 2036  String LSCPServer::GetMidiInstrumentMapp
2036  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2037      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2038      LSCPResultSet result;      LSCPResultSet result;
2039      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2040      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2041      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2042          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2043      }      }
     result.Add(totalMappings);  
2044      return result.Produce();      return result.Produce();
2045  }  }
2046    
# Line 1769  String LSCPServer::GetMidiInstrumentMapp Line 2048  String LSCPServer::GetMidiInstrumentMapp
2048      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2049      LSCPResultSet result;      LSCPResultSet result;
2050      try {      try {
2051          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2052          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2053          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
2054          idx.midi_prog     = MidiProg;  #if WIN32
2055            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2056          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);  #else
2057          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          // assuming POSIX
2058          if (iter == mappings.end()) result.Error("there is no map entry with that index");          const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2059          else { // found  #endif
2060              result.Add("NAME", iter->second.Name);  
2061              result.Add("ENGINE_NAME", iter->second.EngineName);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2062              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          result.Add("ENGINE_NAME", entry.EngineName);
2063              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);          result.Add("INSTRUMENT_FILE", instrumentFileName);
2064              String instrumentName;          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2065              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);          String instrumentName;
2066              if (pEngine) {          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2067                  if (pEngine->GetInstrumentManager()) {          if (pEngine) {
2068                      InstrumentManager::instrument_id_t instrID;              if (pEngine->GetInstrumentManager()) {
2069                      instrID.FileName = iter->second.InstrumentFile;                  InstrumentManager::instrument_id_t instrID;
2070                      instrID.Index    = iter->second.InstrumentIndex;                  instrID.FileName = entry.InstrumentFile;
2071                      instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);                  instrID.Index    = entry.InstrumentIndex;
2072                  }                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                 EngineFactory::Destroy(pEngine);  
2073              }              }
2074              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);  
2075          }          }
2076            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2077            switch (entry.LoadMode) {
2078                case MidiInstrumentMapper::ON_DEMAND:
2079                    result.Add("LOAD_MODE", "ON_DEMAND");
2080                    break;
2081                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2082                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2083                    break;
2084                case MidiInstrumentMapper::PERSISTENT:
2085                    result.Add("LOAD_MODE", "PERSISTENT");
2086                    break;
2087                default:
2088                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2089            }
2090            result.Add("VOLUME", entry.Volume);
2091      } catch (Exception e) {      } catch (Exception e) {
2092          result.Error(e);          result.Error(e);
2093      }      }
# Line 1948  String LSCPServer::GetMidiInstrumentMap( Line 2227  String LSCPServer::GetMidiInstrumentMap(
2227      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2228      LSCPResultSet result;      LSCPResultSet result;
2229      try {      try {
2230          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2231          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2232      } catch (Exception e) {      } catch (Exception e) {
2233          result.Error(e);          result.Error(e);
# Line 1979  String LSCPServer::SetChannelMap(uint ui Line 2258  String LSCPServer::SetChannelMap(uint ui
2258      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2259      LSCPResultSet result;      LSCPResultSet result;
2260      try {      try {
2261          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");  
2262    
2263          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2264          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 1999  String LSCPServer::CreateFxSend(uint uiS Line 2274  String LSCPServer::CreateFxSend(uint uiS
2274      LSCPResultSet result;      LSCPResultSet result;
2275      try {      try {
2276          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2277            
2278          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2279          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2280    
# Line 2083  String LSCPServer::GetFxSendInfo(uint ui Line 2358  String LSCPServer::GetFxSendInfo(uint ui
2358      try {      try {
2359          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2360          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2361            
2362          // gather audio routing informations          // gather audio routing informations
2363          String AudioRouting;          String AudioRouting;
2364          for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {          for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
# Line 2092  String LSCPServer::GetFxSendInfo(uint ui Line 2367  String LSCPServer::GetFxSendInfo(uint ui
2367          }          }
2368    
2369          // success          // success
2370          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2371          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2372          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2373          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
# Line 2158  String LSCPServer::SetFxSendLevel(uint u Line 2433  String LSCPServer::SetFxSendLevel(uint u
2433      return result.Produce();      return result.Produce();
2434  }  }
2435    
2436    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2437        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2438        LSCPResultSet result;
2439        try {
2440            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2441            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2442            Engine* pEngine = pEngineChannel->GetEngine();
2443            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2444            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2445            InstrumentManager::instrument_id_t instrumentID;
2446            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2447            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2448            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2449        } catch (Exception e) {
2450            result.Error(e);
2451        }
2452        return result.Produce();
2453    }
2454    
2455    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2456        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2457        LSCPResultSet result;
2458        try {
2459            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2460    
2461            if (Arg1 > 127 || Arg2 > 127) {
2462                throw Exception("Invalid MIDI message");
2463            }
2464    
2465            VirtualMidiDevice* pMidiDevice = NULL;
2466            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2467            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2468                if ((*iter).pEngineChannel == pEngineChannel) {
2469                    pMidiDevice = (*iter).pMidiListener;
2470                    break;
2471                }
2472            }
2473            
2474            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2475    
2476            if (MidiMsg == "NOTE_ON") {
2477                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2478                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2479                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2480            } else if (MidiMsg == "NOTE_OFF") {
2481                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2482                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2483                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2484            } else {
2485                throw Exception("Unknown MIDI message type: " + MidiMsg);
2486            }
2487        } catch (Exception e) {
2488            result.Error(e);
2489        }
2490        return result.Produce();
2491    }
2492    
2493  /**  /**
2494   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2495   */   */
# Line 2165  String LSCPServer::ResetChannel(uint uiS Line 2497  String LSCPServer::ResetChannel(uint uiS
2497      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2498      LSCPResultSet result;      LSCPResultSet result;
2499      try {      try {
2500          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");  
2501          pEngineChannel->Reset();          pEngineChannel->Reset();
2502      }      }
2503      catch (Exception e) {      catch (Exception e) {
# Line 2193  String LSCPServer::ResetSampler() { Line 2522  String LSCPServer::ResetSampler() {
2522   */   */
2523  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2524      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2525        const std::string description =
2526            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2527      LSCPResultSet result;      LSCPResultSet result;
2528      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2529      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2530      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2531  #if HAVE_SQLITE3  #if HAVE_SQLITE3
# Line 2202  String LSCPServer::GetServerInfo() { Line 2533  String LSCPServer::GetServerInfo() {
2533  #else  #else
2534      result.Add("INSTRUMENTS_DB_SUPPORT", "no");      result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2535  #endif  #endif
2536        
2537        return result.Produce();
2538    }
2539    
2540    /**
2541     * Will be called by the parser to return the current number of all active streams.
2542     */
2543    String LSCPServer::GetTotalStreamCount() {
2544        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2545        LSCPResultSet result;
2546        result.Add(pSampler->GetDiskStreamCount());
2547      return result.Produce();      return result.Produce();
2548  }  }
2549    
# Line 2222  String LSCPServer::GetTotalVoiceCount() Line 2563  String LSCPServer::GetTotalVoiceCount()
2563  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
2564      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2565      LSCPResultSet result;      LSCPResultSet result;
2566      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
2567        return result.Produce();
2568    }
2569    
2570    /**
2571     * Will be called by the parser to return the sampler global maximum
2572     * allowed number of voices.
2573     */
2574    String LSCPServer::GetGlobalMaxVoices() {
2575        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
2576        LSCPResultSet result;
2577        result.Add(GLOBAL_MAX_VOICES);
2578        return result.Produce();
2579    }
2580    
2581    /**
2582     * Will be called by the parser to set the sampler global maximum number of
2583     * voices.
2584     */
2585    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
2586        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
2587        LSCPResultSet result;
2588        try {
2589            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
2590            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
2591            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2592            if (engines.size() > 0) {
2593                std::set<Engine*>::iterator iter = engines.begin();
2594                std::set<Engine*>::iterator end  = engines.end();
2595                for (; iter != end; ++iter) {
2596                    (*iter)->SetMaxVoices(iVoices);
2597                }
2598            }
2599            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
2600        } catch (Exception e) {
2601            result.Error(e);
2602        }
2603        return result.Produce();
2604    }
2605    
2606    /**
2607     * Will be called by the parser to return the sampler global maximum
2608     * allowed number of disk streams.
2609     */
2610    String LSCPServer::GetGlobalMaxStreams() {
2611        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
2612        LSCPResultSet result;
2613        result.Add(GLOBAL_MAX_STREAMS);
2614        return result.Produce();
2615    }
2616    
2617    /**
2618     * Will be called by the parser to set the sampler global maximum number of
2619     * disk streams.
2620     */
2621    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
2622        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
2623        LSCPResultSet result;
2624        try {
2625            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
2626            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
2627            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2628            if (engines.size() > 0) {
2629                std::set<Engine*>::iterator iter = engines.begin();
2630                std::set<Engine*>::iterator end  = engines.end();
2631                for (; iter != end; ++iter) {
2632                    (*iter)->SetMaxDiskStreams(iStreams);
2633                }
2634            }
2635            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
2636        } catch (Exception e) {
2637            result.Error(e);
2638        }
2639      return result.Produce();      return result.Produce();
2640  }  }
2641    
# Line 2236  String LSCPServer::SetGlobalVolume(doubl Line 2649  String LSCPServer::SetGlobalVolume(doubl
2649      LSCPResultSet result;      LSCPResultSet result;
2650      try {      try {
2651          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2652          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2653          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2654      } catch (Exception e) {      } catch (Exception e) {
2655          result.Error(e);          result.Error(e);
# Line 2244  String LSCPServer::SetGlobalVolume(doubl Line 2657  String LSCPServer::SetGlobalVolume(doubl
2657      return result.Produce();      return result.Produce();
2658  }  }
2659    
2660    String LSCPServer::GetFileInstruments(String Filename) {
2661        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2662        LSCPResultSet result;
2663        try {
2664            VerifyFile(Filename);
2665        } catch (Exception e) {
2666            result.Error(e);
2667            return result.Produce();
2668        }
2669        // try to find a sampler engine that can handle the file
2670        bool bFound = false;
2671        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2672        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2673            Engine* pEngine = NULL;
2674            try {
2675                pEngine = EngineFactory::Create(engineTypes[i]);
2676                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2677                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2678                if (pManager) {
2679                    std::vector<InstrumentManager::instrument_id_t> IDs =
2680                        pManager->GetInstrumentFileContent(Filename);
2681                    // return the amount of instruments in the file
2682                    result.Add(IDs.size());
2683                    // no more need to ask other engine types
2684                    bFound = true;
2685                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2686            } catch (Exception e) {
2687                // NOOP, as exception is thrown if engine doesn't support file
2688            }
2689            if (pEngine) EngineFactory::Destroy(pEngine);
2690        }
2691    
2692        if (!bFound) result.Error("Unknown file format");
2693        return result.Produce();
2694    }
2695    
2696    String LSCPServer::ListFileInstruments(String Filename) {
2697        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2698        LSCPResultSet result;
2699        try {
2700            VerifyFile(Filename);
2701        } catch (Exception e) {
2702            result.Error(e);
2703            return result.Produce();
2704        }
2705        // try to find a sampler engine that can handle the file
2706        bool bFound = false;
2707        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2708        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2709            Engine* pEngine = NULL;
2710            try {
2711                pEngine = EngineFactory::Create(engineTypes[i]);
2712                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2713                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2714                if (pManager) {
2715                    std::vector<InstrumentManager::instrument_id_t> IDs =
2716                        pManager->GetInstrumentFileContent(Filename);
2717                    // return a list of IDs of the instruments in the file
2718                    String s;
2719                    for (int j = 0; j < IDs.size(); j++) {
2720                        if (s.size()) s += ",";
2721                        s += ToString(IDs[j].Index);
2722                    }
2723                    result.Add(s);
2724                    // no more need to ask other engine types
2725                    bFound = true;
2726                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2727            } catch (Exception e) {
2728                // NOOP, as exception is thrown if engine doesn't support file
2729            }
2730            if (pEngine) EngineFactory::Destroy(pEngine);
2731        }
2732    
2733        if (!bFound) result.Error("Unknown file format");
2734        return result.Produce();
2735    }
2736    
2737    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2738        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2739        LSCPResultSet result;
2740        try {
2741            VerifyFile(Filename);
2742        } catch (Exception e) {
2743            result.Error(e);
2744            return result.Produce();
2745        }
2746        InstrumentManager::instrument_id_t id;
2747        id.FileName = Filename;
2748        id.Index    = InstrumentID;
2749        // try to find a sampler engine that can handle the file
2750        bool bFound = false;
2751        bool bFatalErr = false;
2752        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2753        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2754            Engine* pEngine = NULL;
2755            try {
2756                pEngine = EngineFactory::Create(engineTypes[i]);
2757                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2758                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2759                if (pManager) {
2760                    // check if the instrument index is valid
2761                    // FIXME: this won't work if an engine only supports parts of the instrument file
2762                    std::vector<InstrumentManager::instrument_id_t> IDs =
2763                        pManager->GetInstrumentFileContent(Filename);
2764                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2765                        std::stringstream ss;
2766                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2767                        bFatalErr = true;
2768                        throw Exception(ss.str());
2769                    }
2770                    // get the info of the requested instrument
2771                    InstrumentManager::instrument_info_t info =
2772                        pManager->GetInstrumentInfo(id);
2773                    // return detailed informations about the file
2774                    result.Add("NAME", info.InstrumentName);
2775                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2776                    result.Add("FORMAT_VERSION", info.FormatVersion);
2777                    result.Add("PRODUCT", info.Product);
2778                    result.Add("ARTISTS", info.Artists);
2779    
2780                    std::stringstream ss;
2781                    bool b = false;
2782                    for (int i = 0; i < 128; i++) {
2783                        if (info.KeyBindings[i]) {
2784                            if (b) ss << ',';
2785                            ss << i; b = true;
2786                        }
2787                    }
2788                    result.Add("KEY_BINDINGS", ss.str());
2789    
2790                    b = false;
2791                    std::stringstream ss2;
2792                    for (int i = 0; i < 128; i++) {
2793                        if (info.KeySwitchBindings[i]) {
2794                            if (b) ss2 << ',';
2795                            ss2 << i; b = true;
2796                        }
2797                    }
2798                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
2799                    // no more need to ask other engine types
2800                    bFound = true;
2801                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2802            } catch (Exception e) {
2803                // usually NOOP, as exception is thrown if engine doesn't support file
2804                if (bFatalErr) result.Error(e);
2805            }
2806            if (pEngine) EngineFactory::Destroy(pEngine);
2807        }
2808    
2809        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2810        return result.Produce();
2811    }
2812    
2813    void LSCPServer::VerifyFile(String Filename) {
2814        #if WIN32
2815        WIN32_FIND_DATA win32FileAttributeData;
2816        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2817        if (!res) {
2818            std::stringstream ss;
2819            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2820            throw Exception(ss.str());
2821        }
2822        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2823            throw Exception("Directory is specified");
2824        }
2825        #else
2826        File f(Filename);
2827        if(!f.Exist()) throw Exception(f.GetErrorMsg());
2828        if (f.IsDirectory()) throw Exception("Directory is specified");
2829        #endif
2830    }
2831    
2832  /**  /**
2833   * 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
2834   * server for receiving event messages.   * server for receiving event messages.
# Line 2325  String LSCPServer::GetDbInstrumentDirect Line 2910  String LSCPServer::GetDbInstrumentDirect
2910    
2911          for (int i = 0; i < dirs->size(); i++) {          for (int i = 0; i < dirs->size(); i++) {
2912              if (list != "") list += ",";              if (list != "") list += ",";
2913              list += "'" + dirs->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2914          }          }
2915    
2916          result.Add(list);          result.Add(list);
# Line 2345  String LSCPServer::GetDbInstrumentDirect Line 2930  String LSCPServer::GetDbInstrumentDirect
2930      try {      try {
2931          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2932    
2933          result.Add("DESCRIPTION", info.Description);          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2934          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2935          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2936      } catch (Exception e) {      } catch (Exception e) {
# Line 2435  String LSCPServer::AddDbInstruments(Stri Line 3020  String LSCPServer::AddDbInstruments(Stri
3020      return result.Produce();      return result.Produce();
3021  }  }
3022    
3023  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3024      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));
3025      LSCPResultSet result;      LSCPResultSet result;
3026  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3027      try {      try {
3028          int id;          int id;
3029          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3030          if (ScanMode.compare("RECURSIVE") == 0) {          if (ScanMode.compare("RECURSIVE") == 0) {
3031             id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3032          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3033             id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3034          } else if (ScanMode.compare("FLAT") == 0) {          } else if (ScanMode.compare("FLAT") == 0) {
3035             id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);              id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3036          } else {          } else {
3037              throw Exception("Unknown scan mode: " + ScanMode);              throw Exception("Unknown scan mode: " + ScanMode);
3038          }          }
3039            
3040          if (bBackground) result = id;          if (bBackground) result = id;
3041      } catch (Exception e) {      } catch (Exception e) {
3042           result.Error(e);           result.Error(e);
# Line 2502  String LSCPServer::GetDbInstruments(Stri Line 3087  String LSCPServer::GetDbInstruments(Stri
3087    
3088          for (int i = 0; i < instrs->size(); i++) {          for (int i = 0; i < instrs->size(); i++) {
3089              if (list != "") list += ",";              if (list != "") list += ",";
3090              list += "'" + instrs->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
3091          }          }
3092    
3093          result.Add(list);          result.Add(list);
# Line 2529  String LSCPServer::GetDbInstrumentInfo(S Line 3114  String LSCPServer::GetDbInstrumentInfo(S
3114          result.Add("SIZE", (int)info.Size);          result.Add("SIZE", (int)info.Size);
3115          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
3116          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
3117          result.Add("DESCRIPTION", FilterEndlines(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3118          result.Add("IS_DRUM", info.IsDrum);          result.Add("IS_DRUM", info.IsDrum);
3119          result.Add("PRODUCT", FilterEndlines(info.Product));          result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3120          result.Add("ARTISTS", FilterEndlines(info.Artists));          result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3121          result.Add("KEYWORDS", FilterEndlines(info.Keywords));          result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3122      } catch (Exception e) {      } catch (Exception e) {
3123           result.Error(e);           result.Error(e);
3124      }      }
# Line 2623  String LSCPServer::SetDbInstrumentDescri Line 3208  String LSCPServer::SetDbInstrumentDescri
3208      return result.Produce();      return result.Produce();
3209  }  }
3210    
3211    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3212        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3213        LSCPResultSet result;
3214    #if HAVE_SQLITE3
3215        try {
3216            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3217        } catch (Exception e) {
3218             result.Error(e);
3219        }
3220    #else
3221        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3222    #endif
3223        return result.Produce();
3224    }
3225    
3226    String LSCPServer::FindLostDbInstrumentFiles() {
3227        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3228        LSCPResultSet result;
3229    #if HAVE_SQLITE3
3230        try {
3231            String list;
3232            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3233    
3234            for (int i = 0; i < pLostFiles->size(); i++) {
3235                if (list != "") list += ",";
3236                list += "'" + pLostFiles->at(i) + "'";
3237            }
3238    
3239            result.Add(list);
3240        } catch (Exception e) {
3241             result.Error(e);
3242        }
3243    #else
3244        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3245    #endif
3246        return result.Produce();
3247    }
3248    
3249  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3250      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3251      LSCPResultSet result;      LSCPResultSet result;
# Line 2650  String LSCPServer::FindDbInstrumentDirec Line 3273  String LSCPServer::FindDbInstrumentDirec
3273    
3274          for (int i = 0; i < pDirectories->size(); i++) {          for (int i = 0; i < pDirectories->size(); i++) {
3275              if (list != "") list += ",";              if (list != "") list += ",";
3276              list += "'" + pDirectories->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3277          }          }
3278    
3279          result.Add(list);          result.Add(list);
# Line 2706  String LSCPServer::FindDbInstruments(Str Line 3329  String LSCPServer::FindDbInstruments(Str
3329    
3330          for (int i = 0; i < pInstruments->size(); i++) {          for (int i = 0; i < pInstruments->size(); i++) {
3331              if (list != "") list += ",";              if (list != "") list += ",";
3332              list += "'" + pInstruments->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3333          }          }
3334    
3335          result.Add(list);          result.Add(list);
# Line 2719  String LSCPServer::FindDbInstruments(Str Line 3342  String LSCPServer::FindDbInstruments(Str
3342      return result.Produce();      return result.Produce();
3343  }  }
3344    
3345    String LSCPServer::FormatInstrumentsDb() {
3346        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3347        LSCPResultSet result;
3348    #if HAVE_SQLITE3
3349        try {
3350            InstrumentsDb::GetInstrumentsDb()->Format();
3351        } catch (Exception e) {
3352             result.Error(e);
3353        }
3354    #else
3355        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3356    #endif
3357        return result.Produce();
3358    }
3359    
3360    
3361  /**  /**
3362   * 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 2739  String LSCPServer::SetEcho(yyparse_param Line 3377  String LSCPServer::SetEcho(yyparse_param
3377      return result.Produce();      return result.Produce();
3378  }  }
3379    
 String LSCPServer::FilterEndlines(String s) {  
     String s2 = s;  
     for (int i = 0; i < s2.length(); i++) {  
         if (s2.at(i) == '\r') s2.at(i) = ' ';  
         else if (s2.at(i) == '\n') s2.at(i) = ' ';  
     }  
       
     return s2;  
3380  }  }

Legend:
Removed from v.1200  
changed lines
  Added in v.1835

  ViewVC Help
Powered by ViewVC