/[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 1133 by iliev, Mon Mar 26 08:27:06 2007 UTC revision 2025 by schoenebeck, Sun Nov 1 18:47:59 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 - 2009 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"
 #include "../common/global.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  # include "sqlite3.h"  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
40  #endif  #endif
41    
42  #include "../engines/EngineFactory.h"  #include "../engines/EngineFactory.h"
# Line 37  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 53  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 61  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 81  LSCPServer::LSCPServer(Sampler* pSampler Line 126  LSCPServer::LSCPServer(Sampler* pSampler
126      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
127      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
128      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
129        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
131        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
132        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
133        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        CloseAllConnections();
145        InstrumentManager::StopBackgroundThread();
146    #if defined(WIN32)
147        if (hSocket >= 0) closesocket(hSocket);
148    #else
149      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
150    #endif
151    }
152    
153    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
154        this->pParent = pParent;
155    }
156    
157    LSCPServer::EventHandler::~EventHandler() {
158        std::vector<midi_listener_entry> l = channelMidiListeners;
159        channelMidiListeners.clear();
160        for (int i = 0; i < l.size(); i++)
161            delete l[i].pMidiListener;
162  }  }
163    
164  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
165      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
166  }  }
167    
168    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
169        pChannel->AddEngineChangeListener(this);
170    }
171    
172    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
173        if (!pChannel->GetEngineChannel()) return;
174        EngineToBeChanged(pChannel->Index());
175    }
176    
177    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
178        SamplerChannel* pSamplerChannel =
179            pParent->pSampler->GetSamplerChannel(ChannelId);
180        if (!pSamplerChannel) return;
181        EngineChannel* pEngineChannel =
182            pSamplerChannel->GetEngineChannel();
183        if (!pEngineChannel) return;
184        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
185            if ((*iter).pEngineChannel == pEngineChannel) {
186                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
187                pEngineChannel->Disconnect(pMidiListener);
188                channelMidiListeners.erase(iter);
189                delete pMidiListener;
190                return;
191            }
192        }
193    }
194    
195    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
196        SamplerChannel* pSamplerChannel =
197            pParent->pSampler->GetSamplerChannel(ChannelId);
198        if (!pSamplerChannel) return;
199        EngineChannel* pEngineChannel =
200            pSamplerChannel->GetEngineChannel();
201        if (!pEngineChannel) return;
202        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
203        pEngineChannel->Connect(pMidiListener);
204        midi_listener_entry entry = {
205            pSamplerChannel, pEngineChannel, pMidiListener
206        };
207        channelMidiListeners.push_back(entry);
208    }
209    
210  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
211      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
212  }  }
# Line 103  void LSCPServer::EventHandler::MidiDevic Line 215  void LSCPServer::EventHandler::MidiDevic
215      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
216  }  }
217    
218    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
219        pDevice->RemoveMidiPortCountListener(this);
220        for (int i = 0; i < pDevice->PortCount(); ++i)
221            MidiPortToBeRemoved(pDevice->GetPort(i));
222    }
223    
224    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
225        pDevice->AddMidiPortCountListener(this);
226        for (int i = 0; i < pDevice->PortCount(); ++i)
227            MidiPortAdded(pDevice->GetPort(i));
228    }
229    
230    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
231        // yet unused
232    }
233    
234    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
235        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
236            if ((*iter).pPort == pPort) {
237                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
238                pPort->Disconnect(pMidiListener);
239                deviceMidiListeners.erase(iter);
240                delete pMidiListener;
241                return;
242            }
243        }
244    }
245    
246    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
247        // find out the device ID
248        std::map<uint, MidiInputDevice*> devices =
249            pParent->pSampler->GetMidiInputDevices();
250        for (
251            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
252            iter != devices.end(); ++iter
253        ) {
254            if (iter->second == pPort->GetDevice()) { // found
255                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
256                pPort->Connect(pMidiListener);
257                device_midi_listener_entry entry = {
258                    pPort, pMidiListener, iter->first
259                };
260                deviceMidiListeners.push_back(entry);
261                return;
262            }
263        }
264    }
265    
266  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
267      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
268  }  }
# Line 139  void LSCPServer::EventHandler::TotalVoic Line 299  void LSCPServer::EventHandler::TotalVoic
299      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
300  }  }
301    
302    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
303        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
304    }
305    
306    #if HAVE_SQLITE3
307    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
308        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
309    }
310    
311    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
312        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
313    }
314    
315    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
316        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
317        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
318        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
319    }
320    
321    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
322        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
323    }
324    
325    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
326        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
327    }
328    
329    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
330        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
331        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
332        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
333    }
334    
335    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
336        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
337    }
338    #endif // HAVE_SQLITE3
339    
340    void LSCPServer::RemoveListeners() {
341        pSampler->RemoveChannelCountListener(&eventHandler);
342        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
343        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
344        pSampler->RemoveVoiceCountListener(&eventHandler);
345        pSampler->RemoveStreamCountListener(&eventHandler);
346        pSampler->RemoveBufferFillListener(&eventHandler);
347        pSampler->RemoveTotalStreamCountListener(&eventHandler);
348        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
349        pSampler->RemoveFxSendCountListener(&eventHandler);
350        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
351        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
352        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
353        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
354    #if HAVE_SQLITE3
355        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
356    #endif
357    }
358    
359  /**  /**
360   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 155  int LSCPServer::WaitUntilInitialized(lon Line 371  int LSCPServer::WaitUntilInitialized(lon
371  }  }
372    
373  int LSCPServer::Main() {  int LSCPServer::Main() {
374            #if defined(WIN32)
375            WSADATA wsaData;
376            int iResult;
377            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
378            if (iResult != 0) {
379                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
380                    exit(EXIT_FAILURE);
381            }
382            #endif
383      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
384      if (hSocket < 0) {      if (hSocket < 0) {
385          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 168  int LSCPServer::Main() { Line 393  int LSCPServer::Main() {
393              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
394                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
395                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
396                        #if defined(WIN32)
397                        closesocket(hSocket);
398                        #else
399                      close(hSocket);                      close(hSocket);
400                        #endif
401                      //return -1;                      //return -1;
402                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
403                  }                  }
# Line 180  int LSCPServer::Main() { Line 409  int LSCPServer::Main() {
409    
410      listen(hSocket, 1);      listen(hSocket, 1);
411      Initialized.Set(true);      Initialized.Set(true);
412        
413      // Registering event listeners      // Registering event listeners
414      pSampler->AddChannelCountListener(&eventHandler);      pSampler->AddChannelCountListener(&eventHandler);
415      pSampler->AddAudioDeviceCountListener(&eventHandler);      pSampler->AddAudioDeviceCountListener(&eventHandler);
# Line 188  int LSCPServer::Main() { Line 417  int LSCPServer::Main() {
417      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
418      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
419      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
420        pSampler->AddTotalStreamCountListener(&eventHandler);
421      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
422      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
423      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
424      MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
425      MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
426      MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
427    #if HAVE_SQLITE3
428        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
429    #endif
430      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
431      sockaddr_in client;      sockaddr_in client;
432      int length = sizeof(client);      int length = sizeof(client);
# Line 205  int LSCPServer::Main() { Line 437  int LSCPServer::Main() {
437      timeval timeout;      timeval timeout;
438    
439      while (true) {      while (true) {
440            #if CONFIG_PTHREAD_TESTCANCEL
441                    TestCancel();
442            #endif
443          // 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
444          {          {
445              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 212  int LSCPServer::Main() { Line 447  int LSCPServer::Main() {
447              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
448              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
449                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
450                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
451                  }                  }
452    
453                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
454                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
455                      if(fxs != NULL && fxs->IsInfoChanged()) {                      if(fxs != NULL && fxs->IsInfoChanged()) {
456                          int chn = (*itEngineChannel)->iSamplerChannelIndex;                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
457                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
458                          fxs->SetInfoChanged(false);                          fxs->SetInfoChanged(false);
459                      }                      }
# Line 226  int LSCPServer::Main() { Line 461  int LSCPServer::Main() {
461              }              }
462          }          }
463    
464            // check if MIDI data arrived on some engine channel
465            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
466                const EventHandler::midi_listener_entry entry =
467                    eventHandler.channelMidiListeners[i];
468                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
469                if (pMidiListener->NotesChanged()) {
470                    for (int iNote = 0; iNote < 128; iNote++) {
471                        if (pMidiListener->NoteChanged(iNote)) {
472                            const bool bActive = pMidiListener->NoteIsActive(iNote);
473                            LSCPServer::SendLSCPNotify(
474                                LSCPEvent(
475                                    LSCPEvent::event_channel_midi,
476                                    entry.pSamplerChannel->Index(),
477                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
478                                    iNote,
479                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
480                                            : pMidiListener->NoteOffVelocity(iNote)
481                                )
482                            );
483                        }
484                    }
485                }
486            }
487    
488            // check if MIDI data arrived on some MIDI device
489            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
490                const EventHandler::device_midi_listener_entry entry =
491                    eventHandler.deviceMidiListeners[i];
492                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
493                if (pMidiListener->NotesChanged()) {
494                    for (int iNote = 0; iNote < 128; iNote++) {
495                        if (pMidiListener->NoteChanged(iNote)) {
496                            const bool bActive = pMidiListener->NoteIsActive(iNote);
497                            LSCPServer::SendLSCPNotify(
498                                LSCPEvent(
499                                    LSCPEvent::event_device_midi,
500                                    entry.uiDeviceID,
501                                    entry.pPort->GetPortNumber(),
502                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
503                                    iNote,
504                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
505                                            : pMidiListener->NoteOffVelocity(iNote)
506                                )
507                            );
508                        }
509                    }
510                }
511            }
512    
513          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
514          NotifyBufferMutex.Lock();          NotifyBufferMutex.Lock();
515          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 244  int LSCPServer::Main() { Line 528  int LSCPServer::Main() {
528    
529          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
530    
531          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
532                  continue; //Nothing try again                  continue; //Nothing try again
533          if (retval == -1) {          if (retval == -1) {
534                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
535                    #if defined(WIN32)
536                    closesocket(hSocket);
537                    #else
538                  close(hSocket);                  close(hSocket);
539                    #endif
540                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
541          }          }
542    
# Line 260  int LSCPServer::Main() { Line 548  int LSCPServer::Main() {
548                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
549                  }                  }
550    
551                    #if defined(WIN32)
552                    u_long nonblock_io = 1;
553                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
554                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
555                      exit(EXIT_FAILURE);
556                    }
557            #else
558                    struct linger linger;
559                    linger.l_onoff = 1;
560                    linger.l_linger = 0;
561                    if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) {
562                        std::cerr << "LSCPServer: Failed to set SO_LINGER\n";
563                    }
564    
565                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
566                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
567                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
568                  }                  }
569                    #endif
570    
571                  // Parser initialization                  // Parser initialization
572                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 287  int LSCPServer::Main() { Line 590  int LSCPServer::Main() {
590                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
591                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
592                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
593                                    itCurrentSession = iter; // another hack
594                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
595                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
596                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
597                                  }                                  }
598                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
599                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
600                                    itCurrentSession = Sessions.end(); // hack as well
601                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
602                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
603                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 320  void LSCPServer::CloseConnection( std::v Line 625  void LSCPServer::CloseConnection( std::v
625          NotifyMutex.Lock();          NotifyMutex.Lock();
626          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
627          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
628            #if defined(WIN32)
629            closesocket(socket);
630            #else
631          close(socket);          close(socket);
632            #endif
633          NotifyMutex.Unlock();          NotifyMutex.Unlock();
634  }  }
635    
636    void LSCPServer::CloseAllConnections() {
637        std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
638        while(iter != Sessions.end()) {
639            CloseConnection(iter);
640            iter = Sessions.begin();
641        }
642    }
643    
644    void LSCPServer::LockRTNotify() {
645        RTNotifyMutex.Lock();
646    }
647    
648    void LSCPServer::UnlockRTNotify() {
649        RTNotifyMutex.Unlock();
650    }
651    
652  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
653          int subs = 0;          int subs = 0;
654          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 385  extern int GetLSCPCommand( void *buf, in Line 710  extern int GetLSCPCommand( void *buf, in
710          return command.size();          return command.size();
711  }  }
712    
713    extern yyparse_param_t* GetCurrentYaccSession() {
714        return &(*itCurrentSession);
715    }
716    
717  /**  /**
718   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
719   * 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 395  bool LSCPServer::GetLSCPCommand( std::ve Line 724  bool LSCPServer::GetLSCPCommand( std::ve
724          char c;          char c;
725          int i = 0;          int i = 0;
726          while (true) {          while (true) {
727                    #if defined(WIN32)
728                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
729                    #else
730                  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
731                    #endif
732                  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
733                          CloseConnection(iter);                          CloseConnection(iter);
734                          break;                          break;
# Line 410  bool LSCPServer::GetLSCPCommand( std::ve Line 743  bool LSCPServer::GetLSCPCommand( std::ve
743                          }                          }
744                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
745                  }                  }
746                    #if defined(WIN32)
747                    if (result == SOCKET_ERROR) {
748                        int wsa_lasterror = WSAGetLastError();
749                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
750                                    return false;
751                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
752                            CloseConnection(iter);
753                            break;
754                    }
755                    #else
756                  if (result == -1) {                  if (result == -1) {
757                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
758                                  return false;                                  return false;
# Line 448  bool LSCPServer::GetLSCPCommand( std::ve Line 791  bool LSCPServer::GetLSCPCommand( std::ve
791                          CloseConnection(iter);                          CloseConnection(iter);
792                          break;                          break;
793                  }                  }
794                    #endif
795          }          }
796          return false;          return false;
797  }  }
# Line 565  String LSCPServer::DestroyMidiInputDevic Line 909  String LSCPServer::DestroyMidiInputDevic
909      return result.Produce();      return result.Produce();
910  }  }
911    
912    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
913        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
914        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
915    
916        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
917        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
918    
919        return pEngineChannel;
920    }
921    
922  /**  /**
923   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
924   */   */
# Line 711  String LSCPServer::GetEngineInfo(String Line 1065  String LSCPServer::GetEngineInfo(String
1065      LockRTNotify();      LockRTNotify();
1066      try {      try {
1067          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1068          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1069          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1070          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1071      }      }
# Line 784  String LSCPServer::GetChannelInfo(uint u Line 1138  String LSCPServer::GetChannelInfo(uint u
1138          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1139          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1140    
1141            // convert the filename into the correct encoding as defined for LSCP
1142            // (especially in terms of special characters -> escape sequences)
1143            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1144    #if WIN32
1145                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1146    #else
1147                // assuming POSIX
1148                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1149    #endif
1150            }
1151    
1152          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1153          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1154          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1155          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1156          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1157          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 806  String LSCPServer::GetVoiceCount(uint ui Line 1171  String LSCPServer::GetVoiceCount(uint ui
1171      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1172      LSCPResultSet result;      LSCPResultSet result;
1173      try {      try {
1174          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");  
1175          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");
1176          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1177      }      }
# Line 827  String LSCPServer::GetStreamCount(uint u Line 1189  String LSCPServer::GetStreamCount(uint u
1189      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1190      LSCPResultSet result;      LSCPResultSet result;
1191      try {      try {
1192          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");  
1193          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");
1194          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1195      }      }
# Line 848  String LSCPServer::GetBufferFill(fill_re Line 1207  String LSCPServer::GetBufferFill(fill_re
1207      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1208      LSCPResultSet result;      LSCPResultSet result;
1209      try {      try {
1210          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");  
1211          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");
1212          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1213          else {          else {
# Line 939  String LSCPServer::GetMidiInputDriverInf Line 1295  String LSCPServer::GetMidiInputDriverInf
1295              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1296                  if (s != "") s += ",";                  if (s != "") s += ",";
1297                  s += iter->first;                  s += iter->first;
1298                    delete iter->second;
1299              }              }
1300              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1301          }          }
# Line 963  String LSCPServer::GetAudioOutputDriverI Line 1320  String LSCPServer::GetAudioOutputDriverI
1320              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1321                  if (s != "") s += ",";                  if (s != "") s += ",";
1322                  s += iter->first;                  s += iter->first;
1323                    delete iter->second;
1324              }              }
1325              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1326          }          }
# Line 993  String LSCPServer::GetMidiInputDriverPar Line 1351  String LSCPServer::GetMidiInputDriverPar
1351          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1352          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1353          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1354            delete pParameter;
1355      }      }
1356      catch (Exception e) {      catch (Exception e) {
1357          result.Error(e);          result.Error(e);
# Line 1020  String LSCPServer::GetAudioOutputDriverP Line 1379  String LSCPServer::GetAudioOutputDriverP
1379          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1380          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1381          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1382            delete pParameter;
1383      }      }
1384      catch (Exception e) {      catch (Exception e) {
1385          result.Error(e);          result.Error(e);
# Line 1486  String LSCPServer::SetMIDIInputType(Stri Line 1846  String LSCPServer::SetMIDIInputType(Stri
1846              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1847              // Make it with at least one initial port.              // Make it with at least one initial port.
1848              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
             parameters["PORTS"]->SetValue("1");  
1849          }          }
1850          // Must have a device...          // Must have a device...
1851          if (pDevice == NULL)          if (pDevice == NULL)
# Line 1529  String LSCPServer::SetVolume(double dVol Line 1888  String LSCPServer::SetVolume(double dVol
1888      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, 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          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
1893      }      }
1894      catch (Exception e) {      catch (Exception e) {
# Line 1548  String LSCPServer::SetChannelMute(bool b Line 1904  String LSCPServer::SetChannelMute(bool b
1904      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1905      LSCPResultSet result;      LSCPResultSet result;
1906      try {      try {
1907          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");  
1908    
1909          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1910          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1569  String LSCPServer::SetChannelSolo(bool b Line 1921  String LSCPServer::SetChannelSolo(bool b
1921      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1922      LSCPResultSet result;      LSCPResultSet result;
1923      try {      try {
1924          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");  
1925    
1926          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1927          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
# Line 1693  String LSCPServer::GetMidiInstrumentMapp Line 2041  String LSCPServer::GetMidiInstrumentMapp
2041      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2042      LSCPResultSet result;      LSCPResultSet result;
2043      try {      try {
2044          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2045      } catch (Exception e) {      } catch (Exception e) {
2046          result.Error(e);          result.Error(e);
2047      }      }
# Line 1704  String LSCPServer::GetMidiInstrumentMapp Line 2052  String LSCPServer::GetMidiInstrumentMapp
2052  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2053      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2054      LSCPResultSet result;      LSCPResultSet result;
2055      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2056      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2057      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2058          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2059      }      }
     result.Add(totalMappings);  
2060      return result.Produce();      return result.Produce();
2061  }  }
2062    
# Line 1719  String LSCPServer::GetMidiInstrumentMapp Line 2064  String LSCPServer::GetMidiInstrumentMapp
2064      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2065      LSCPResultSet result;      LSCPResultSet result;
2066      try {      try {
2067          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2068          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2069          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
2070          idx.midi_prog     = MidiProg;  #if WIN32
2071            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2072    #else
2073            // assuming POSIX
2074            const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2075    #endif
2076    
2077          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2078          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          result.Add("ENGINE_NAME", entry.EngineName);
2079          if (iter == mappings.end()) result.Error("there is no map entry with that index");          result.Add("INSTRUMENT_FILE", instrumentFileName);
2080          else { // found          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2081              result.Add("NAME", iter->second.Name);          String instrumentName;
2082              result.Add("ENGINE_NAME", iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2083              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          if (pEngine) {
2084              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              if (pEngine->GetInstrumentManager()) {
2085              String instrumentName;                  InstrumentManager::instrument_id_t instrID;
2086              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);                  instrID.FileName = entry.InstrumentFile;
2087              if (pEngine) {                  instrID.Index    = entry.InstrumentIndex;
2088                  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);  
             }  
             result.Add("INSTRUMENT_NAME", instrumentName);  
             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!");  
2089              }              }
2090              result.Add("VOLUME", iter->second.Volume);              EngineFactory::Destroy(pEngine);
2091            }
2092            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2093            switch (entry.LoadMode) {
2094                case MidiInstrumentMapper::ON_DEMAND:
2095                    result.Add("LOAD_MODE", "ON_DEMAND");
2096                    break;
2097                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2098                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2099                    break;
2100                case MidiInstrumentMapper::PERSISTENT:
2101                    result.Add("LOAD_MODE", "PERSISTENT");
2102                    break;
2103                default:
2104                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2105          }          }
2106            result.Add("VOLUME", entry.Volume);
2107      } catch (Exception e) {      } catch (Exception e) {
2108          result.Error(e);          result.Error(e);
2109      }      }
# Line 1898  String LSCPServer::GetMidiInstrumentMap( Line 2243  String LSCPServer::GetMidiInstrumentMap(
2243      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2244      LSCPResultSet result;      LSCPResultSet result;
2245      try {      try {
2246          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2247            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2248      } catch (Exception e) {      } catch (Exception e) {
2249          result.Error(e);          result.Error(e);
2250      }      }
# Line 1928  String LSCPServer::SetChannelMap(uint ui Line 2274  String LSCPServer::SetChannelMap(uint ui
2274      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2275      LSCPResultSet result;      LSCPResultSet result;
2276      try {      try {
2277          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");  
2278    
2279          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2280          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 1947  String LSCPServer::CreateFxSend(uint uiS Line 2289  String LSCPServer::CreateFxSend(uint uiS
2289      dmsg(2,("LSCPServer: CreateFxSend()\n"));      dmsg(2,("LSCPServer: CreateFxSend()\n"));
2290      LSCPResultSet result;      LSCPResultSet result;
2291      try {      try {
2292          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");  
2293    
2294          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2295          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)");
# Line 1967  String LSCPServer::DestroyFxSend(uint ui Line 2305  String LSCPServer::DestroyFxSend(uint ui
2305      dmsg(2,("LSCPServer: DestroyFxSend()\n"));      dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2306      LSCPResultSet result;      LSCPResultSet result;
2307      try {      try {
2308          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");  
2309    
2310          FxSend* pFxSend = NULL;          FxSend* pFxSend = NULL;
2311          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
# Line 1992  String LSCPServer::GetFxSends(uint uiSam Line 2326  String LSCPServer::GetFxSends(uint uiSam
2326      dmsg(2,("LSCPServer: GetFxSends()\n"));      dmsg(2,("LSCPServer: GetFxSends()\n"));
2327      LSCPResultSet result;      LSCPResultSet result;
2328      try {      try {
2329          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");  
2330    
2331          result.Add(pEngineChannel->GetFxSendCount());          result.Add(pEngineChannel->GetFxSendCount());
2332      } catch (Exception e) {      } catch (Exception e) {
# Line 2010  String LSCPServer::ListFxSends(uint uiSa Line 2340  String LSCPServer::ListFxSends(uint uiSa
2340      LSCPResultSet result;      LSCPResultSet result;
2341      String list;      String list;
2342      try {      try {
2343          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");  
2344    
2345          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2346              FxSend* pFxSend = pEngineChannel->GetFxSend(i);              FxSend* pFxSend = pEngineChannel->GetFxSend(i);
# Line 2028  String LSCPServer::ListFxSends(uint uiSa Line 2354  String LSCPServer::ListFxSends(uint uiSa
2354      return result.Produce();      return result.Produce();
2355  }  }
2356    
2357    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2358        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2359    
2360        FxSend* pFxSend = NULL;
2361        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2362            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2363                pFxSend = pEngineChannel->GetFxSend(i);
2364                break;
2365            }
2366        }
2367        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2368        return pFxSend;
2369    }
2370    
2371  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2372      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2373      LSCPResultSet result;      LSCPResultSet result;
2374      try {      try {
2375          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2376          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2377    
2378          // gather audio routing informations          // gather audio routing informations
2379          String AudioRouting;          String AudioRouting;
# Line 2055  String LSCPServer::GetFxSendInfo(uint ui Line 2383  String LSCPServer::GetFxSendInfo(uint ui
2383          }          }
2384    
2385          // success          // success
2386          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2387          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2388          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2389          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
# Line 2065  String LSCPServer::GetFxSendInfo(uint ui Line 2393  String LSCPServer::GetFxSendInfo(uint ui
2393      return result.Produce();      return result.Produce();
2394  }  }
2395    
2396  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {  String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2397      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));      dmsg(2,("LSCPServer: SetFxSendName()\n"));
2398      LSCPResultSet result;      LSCPResultSet result;
2399      try {      try {
2400          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2401    
2402          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetName(Name);
2403          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2404        } catch (Exception e) {
2405            result.Error(e);
2406        }
2407        return result.Produce();
2408    }
2409    
2410          FxSend* pFxSend = NULL;  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2411          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2412              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2413                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2414                  break;          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2415    
2416          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2417          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2096  String LSCPServer::SetFxSendMidiControll Line 2425  String LSCPServer::SetFxSendMidiControll
2425      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2426      LSCPResultSet result;      LSCPResultSet result;
2427      try {      try {
2428          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         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");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2429    
2430          pFxSend->SetMidiController(MidiController);          pFxSend->SetMidiController(MidiController);
2431          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2123  String LSCPServer::SetFxSendLevel(uint u Line 2439  String LSCPServer::SetFxSendLevel(uint u
2439      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2440      LSCPResultSet result;      LSCPResultSet result;
2441      try {      try {
2442          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2443    
2444          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetLevel((float)dLevel);
2445          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2446        } catch (Exception e) {
2447            result.Error(e);
2448        }
2449        return result.Produce();
2450    }
2451    
2452          FxSend* pFxSend = NULL;  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2453          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2454              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2455                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2456            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2457            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2458            Engine* pEngine = pEngineChannel->GetEngine();
2459            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2460            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2461            InstrumentManager::instrument_id_t instrumentID;
2462            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2463            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2464            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2465        } catch (Exception e) {
2466            result.Error(e);
2467        }
2468        return result.Produce();
2469    }
2470    
2471    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2472        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2473        LSCPResultSet result;
2474        try {
2475            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2476    
2477            if (Arg1 > 127 || Arg2 > 127) {
2478                throw Exception("Invalid MIDI message");
2479            }
2480    
2481            VirtualMidiDevice* pMidiDevice = NULL;
2482            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2483            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2484                if ((*iter).pEngineChannel == pEngineChannel) {
2485                    pMidiDevice = (*iter).pMidiListener;
2486                  break;                  break;
2487              }              }
2488          }          }
2489          if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");          
2490            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2491    
2492          pFxSend->SetLevel((float)dLevel);          if (MidiMsg == "NOTE_ON") {
2493          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));              pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2494                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2495                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2496            } else if (MidiMsg == "NOTE_OFF") {
2497                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2498                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2499                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2500            } else if (MidiMsg == "CC") {
2501                pMidiDevice->SendCCToDevice(Arg1, Arg2);
2502                bool b = pMidiDevice->SendCCToSampler(Arg1, Arg2);
2503                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2504            } else {
2505                throw Exception("Unknown MIDI message type: " + MidiMsg);
2506            }
2507      } catch (Exception e) {      } catch (Exception e) {
2508          result.Error(e);          result.Error(e);
2509      }      }
# Line 2153  String LSCPServer::ResetChannel(uint uiS Line 2517  String LSCPServer::ResetChannel(uint uiS
2517      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2518      LSCPResultSet result;      LSCPResultSet result;
2519      try {      try {
2520          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");  
2521          pEngineChannel->Reset();          pEngineChannel->Reset();
2522      }      }
2523      catch (Exception e) {      catch (Exception e) {
# Line 2181  String LSCPServer::ResetSampler() { Line 2542  String LSCPServer::ResetSampler() {
2542   */   */
2543  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2544      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2545        const std::string description =
2546            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2547      LSCPResultSet result;      LSCPResultSet result;
2548      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2549      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2550      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2551    #if HAVE_SQLITE3
2552        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2553    #else
2554        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2555    #endif
2556    
2557        return result.Produce();
2558    }
2559    
2560    /**
2561     * Will be called by the parser to return the current number of all active streams.
2562     */
2563    String LSCPServer::GetTotalStreamCount() {
2564        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2565        LSCPResultSet result;
2566        result.Add(pSampler->GetDiskStreamCount());
2567      return result.Produce();      return result.Produce();
2568  }  }
2569    
# Line 2204  String LSCPServer::GetTotalVoiceCount() Line 2583  String LSCPServer::GetTotalVoiceCount()
2583  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
2584      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2585      LSCPResultSet result;      LSCPResultSet result;
2586      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
2587        return result.Produce();
2588    }
2589    
2590    /**
2591     * Will be called by the parser to return the sampler global maximum
2592     * allowed number of voices.
2593     */
2594    String LSCPServer::GetGlobalMaxVoices() {
2595        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
2596        LSCPResultSet result;
2597        result.Add(GLOBAL_MAX_VOICES);
2598        return result.Produce();
2599    }
2600    
2601    /**
2602     * Will be called by the parser to set the sampler global maximum number of
2603     * voices.
2604     */
2605    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
2606        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
2607        LSCPResultSet result;
2608        try {
2609            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
2610            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
2611            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2612            if (engines.size() > 0) {
2613                std::set<Engine*>::iterator iter = engines.begin();
2614                std::set<Engine*>::iterator end  = engines.end();
2615                for (; iter != end; ++iter) {
2616                    (*iter)->SetMaxVoices(iVoices);
2617                }
2618            }
2619            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
2620        } catch (Exception e) {
2621            result.Error(e);
2622        }
2623        return result.Produce();
2624    }
2625    
2626    /**
2627     * Will be called by the parser to return the sampler global maximum
2628     * allowed number of disk streams.
2629     */
2630    String LSCPServer::GetGlobalMaxStreams() {
2631        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
2632        LSCPResultSet result;
2633        result.Add(GLOBAL_MAX_STREAMS);
2634        return result.Produce();
2635    }
2636    
2637    /**
2638     * Will be called by the parser to set the sampler global maximum number of
2639     * disk streams.
2640     */
2641    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
2642        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
2643        LSCPResultSet result;
2644        try {
2645            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
2646            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
2647            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2648            if (engines.size() > 0) {
2649                std::set<Engine*>::iterator iter = engines.begin();
2650                std::set<Engine*>::iterator end  = engines.end();
2651                for (; iter != end; ++iter) {
2652                    (*iter)->SetMaxDiskStreams(iStreams);
2653                }
2654            }
2655            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
2656        } catch (Exception e) {
2657            result.Error(e);
2658        }
2659      return result.Produce();      return result.Produce();
2660  }  }
2661    
# Line 2218  String LSCPServer::SetGlobalVolume(doubl Line 2669  String LSCPServer::SetGlobalVolume(doubl
2669      LSCPResultSet result;      LSCPResultSet result;
2670      try {      try {
2671          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2672          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2673          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2674      } catch (Exception e) {      } catch (Exception e) {
2675          result.Error(e);          result.Error(e);
# Line 2226  String LSCPServer::SetGlobalVolume(doubl Line 2677  String LSCPServer::SetGlobalVolume(doubl
2677      return result.Produce();      return result.Produce();
2678  }  }
2679    
2680    String LSCPServer::GetFileInstruments(String Filename) {
2681        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2682        LSCPResultSet result;
2683        try {
2684            VerifyFile(Filename);
2685        } catch (Exception e) {
2686            result.Error(e);
2687            return result.Produce();
2688        }
2689        // try to find a sampler engine that can handle the file
2690        bool bFound = false;
2691        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2692        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2693            Engine* pEngine = NULL;
2694            try {
2695                pEngine = EngineFactory::Create(engineTypes[i]);
2696                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2697                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2698                if (pManager) {
2699                    std::vector<InstrumentManager::instrument_id_t> IDs =
2700                        pManager->GetInstrumentFileContent(Filename);
2701                    // return the amount of instruments in the file
2702                    result.Add(IDs.size());
2703                    // no more need to ask other engine types
2704                    bFound = true;
2705                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2706            } catch (Exception e) {
2707                // NOOP, as exception is thrown if engine doesn't support file
2708            }
2709            if (pEngine) EngineFactory::Destroy(pEngine);
2710        }
2711    
2712        if (!bFound) result.Error("Unknown file format");
2713        return result.Produce();
2714    }
2715    
2716    String LSCPServer::ListFileInstruments(String Filename) {
2717        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2718        LSCPResultSet result;
2719        try {
2720            VerifyFile(Filename);
2721        } catch (Exception e) {
2722            result.Error(e);
2723            return result.Produce();
2724        }
2725        // try to find a sampler engine that can handle the file
2726        bool bFound = false;
2727        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2728        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2729            Engine* pEngine = NULL;
2730            try {
2731                pEngine = EngineFactory::Create(engineTypes[i]);
2732                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2733                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2734                if (pManager) {
2735                    std::vector<InstrumentManager::instrument_id_t> IDs =
2736                        pManager->GetInstrumentFileContent(Filename);
2737                    // return a list of IDs of the instruments in the file
2738                    String s;
2739                    for (int j = 0; j < IDs.size(); j++) {
2740                        if (s.size()) s += ",";
2741                        s += ToString(IDs[j].Index);
2742                    }
2743                    result.Add(s);
2744                    // no more need to ask other engine types
2745                    bFound = true;
2746                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2747            } catch (Exception e) {
2748                // NOOP, as exception is thrown if engine doesn't support file
2749            }
2750            if (pEngine) EngineFactory::Destroy(pEngine);
2751        }
2752    
2753        if (!bFound) result.Error("Unknown file format");
2754        return result.Produce();
2755    }
2756    
2757    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2758        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2759        LSCPResultSet result;
2760        try {
2761            VerifyFile(Filename);
2762        } catch (Exception e) {
2763            result.Error(e);
2764            return result.Produce();
2765        }
2766        InstrumentManager::instrument_id_t id;
2767        id.FileName = Filename;
2768        id.Index    = InstrumentID;
2769        // try to find a sampler engine that can handle the file
2770        bool bFound = false;
2771        bool bFatalErr = false;
2772        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2773        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2774            Engine* pEngine = NULL;
2775            try {
2776                pEngine = EngineFactory::Create(engineTypes[i]);
2777                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2778                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2779                if (pManager) {
2780                    // check if the instrument index is valid
2781                    // FIXME: this won't work if an engine only supports parts of the instrument file
2782                    std::vector<InstrumentManager::instrument_id_t> IDs =
2783                        pManager->GetInstrumentFileContent(Filename);
2784                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2785                        std::stringstream ss;
2786                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2787                        bFatalErr = true;
2788                        throw Exception(ss.str());
2789                    }
2790                    // get the info of the requested instrument
2791                    InstrumentManager::instrument_info_t info =
2792                        pManager->GetInstrumentInfo(id);
2793                    // return detailed informations about the file
2794                    result.Add("NAME", info.InstrumentName);
2795                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2796                    result.Add("FORMAT_VERSION", info.FormatVersion);
2797                    result.Add("PRODUCT", info.Product);
2798                    result.Add("ARTISTS", info.Artists);
2799    
2800                    std::stringstream ss;
2801                    bool b = false;
2802                    for (int i = 0; i < 128; i++) {
2803                        if (info.KeyBindings[i]) {
2804                            if (b) ss << ',';
2805                            ss << i; b = true;
2806                        }
2807                    }
2808                    result.Add("KEY_BINDINGS", ss.str());
2809    
2810                    b = false;
2811                    std::stringstream ss2;
2812                    for (int i = 0; i < 128; i++) {
2813                        if (info.KeySwitchBindings[i]) {
2814                            if (b) ss2 << ',';
2815                            ss2 << i; b = true;
2816                        }
2817                    }
2818                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
2819                    // no more need to ask other engine types
2820                    bFound = true;
2821                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2822            } catch (Exception e) {
2823                // usually NOOP, as exception is thrown if engine doesn't support file
2824                if (bFatalErr) result.Error(e);
2825            }
2826            if (pEngine) EngineFactory::Destroy(pEngine);
2827        }
2828    
2829        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2830        return result.Produce();
2831    }
2832    
2833    void LSCPServer::VerifyFile(String Filename) {
2834        #if WIN32
2835        WIN32_FIND_DATA win32FileAttributeData;
2836        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2837        if (!res) {
2838            std::stringstream ss;
2839            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2840            throw Exception(ss.str());
2841        }
2842        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2843            throw Exception("Directory is specified");
2844        }
2845        #else
2846        File f(Filename);
2847        if(!f.Exist()) throw Exception(f.GetErrorMsg());
2848        if (f.IsDirectory()) throw Exception("Directory is specified");
2849        #endif
2850    }
2851    
2852  /**  /**
2853   * 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
2854   * server for receiving event messages.   * server for receiving event messages.
# Line 2252  String LSCPServer::UnsubscribeNotificati Line 2875  String LSCPServer::UnsubscribeNotificati
2875      return result.Produce();      return result.Produce();
2876  }  }
2877    
2878  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2879                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2880  {      LSCPResultSet result;
2881      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2882      resultSet->Add(argc, argv);      try {
2883      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2884        } catch (Exception e) {
2885             result.Error(e);
2886        }
2887    #else
2888        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2889    #endif
2890        return result.Produce();
2891    }
2892    
2893    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2894        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2895        LSCPResultSet result;
2896    #if HAVE_SQLITE3
2897        try {
2898            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2899        } catch (Exception e) {
2900             result.Error(e);
2901        }
2902    #else
2903        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2904    #endif
2905        return result.Produce();
2906    }
2907    
2908    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2909        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2910        LSCPResultSet result;
2911    #if HAVE_SQLITE3
2912        try {
2913            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2914        } catch (Exception e) {
2915             result.Error(e);
2916        }
2917    #else
2918        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2919    #endif
2920        return result.Produce();
2921    }
2922    
2923    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2924        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2925        LSCPResultSet result;
2926    #if HAVE_SQLITE3
2927        try {
2928            String list;
2929            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2930    
2931            for (int i = 0; i < dirs->size(); i++) {
2932                if (list != "") list += ",";
2933                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2934            }
2935    
2936            result.Add(list);
2937        } catch (Exception e) {
2938             result.Error(e);
2939        }
2940    #else
2941        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2942    #endif
2943        return result.Produce();
2944    }
2945    
2946    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2947        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2948        LSCPResultSet result;
2949    #if HAVE_SQLITE3
2950        try {
2951            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2952    
2953            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2954            result.Add("CREATED", info.Created);
2955            result.Add("MODIFIED", info.Modified);
2956        } catch (Exception e) {
2957             result.Error(e);
2958        }
2959    #else
2960        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2961    #endif
2962        return result.Produce();
2963    }
2964    
2965    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2966        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2967        LSCPResultSet result;
2968    #if HAVE_SQLITE3
2969        try {
2970            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2971        } catch (Exception e) {
2972             result.Error(e);
2973        }
2974    #else
2975        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2976    #endif
2977        return result.Produce();
2978    }
2979    
2980    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2981        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2982        LSCPResultSet result;
2983    #if HAVE_SQLITE3
2984        try {
2985            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2986        } catch (Exception e) {
2987             result.Error(e);
2988        }
2989    #else
2990        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2991    #endif
2992        return result.Produce();
2993    }
2994    
2995    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2996        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2997        LSCPResultSet result;
2998    #if HAVE_SQLITE3
2999        try {
3000            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
3001        } catch (Exception e) {
3002             result.Error(e);
3003        }
3004    #else
3005        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3006    #endif
3007        return result.Produce();
3008    }
3009    
3010    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
3011        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
3012        LSCPResultSet result;
3013    #if HAVE_SQLITE3
3014        try {
3015            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
3016        } catch (Exception e) {
3017             result.Error(e);
3018        }
3019    #else
3020        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3021    #endif
3022        return result.Produce();
3023    }
3024    
3025    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
3026        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
3027        LSCPResultSet result;
3028    #if HAVE_SQLITE3
3029        try {
3030            int id;
3031            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3032            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
3033            if (bBackground) result = id;
3034        } catch (Exception e) {
3035             result.Error(e);
3036        }
3037    #else
3038        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3039    #endif
3040        return result.Produce();
3041  }  }
3042    
3043  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3044        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));
3045      LSCPResultSet result;      LSCPResultSet result;
3046  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3047      char* zErrMsg = NULL;      try {
3048      sqlite3 *db;          int id;
3049      String selectStr = "SELECT " + query;          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3050            if (ScanMode.compare("RECURSIVE") == 0) {
3051                id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3052            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3053                id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3054            } else if (ScanMode.compare("FLAT") == 0) {
3055                id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3056            } else {
3057                throw Exception("Unknown scan mode: " + ScanMode);
3058            }
3059    
3060            if (bBackground) result = id;
3061        } catch (Exception e) {
3062             result.Error(e);
3063        }
3064    #else
3065        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3066    #endif
3067        return result.Produce();
3068    }
3069    
3070      int rc = sqlite3_open("linuxsampler.db", &db);  String LSCPServer::RemoveDbInstrument(String Instr) {
3071      if (rc == SQLITE_OK)      dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
3072      {      LSCPResultSet result;
3073              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);  #if HAVE_SQLITE3
3074        try {
3075            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
3076        } catch (Exception e) {
3077             result.Error(e);
3078      }      }
3079      if ( rc != SQLITE_OK )  #else
3080      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3081              result.Error(String(zErrMsg), rc);  #endif
3082        return result.Produce();
3083    }
3084    
3085    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
3086        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3087        LSCPResultSet result;
3088    #if HAVE_SQLITE3
3089        try {
3090            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
3091        } catch (Exception e) {
3092             result.Error(e);
3093      }      }
     sqlite3_close(db);  
3094  #else  #else
3095      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3096  #endif  #endif
3097      return result.Produce();      return result.Produce();
3098  }  }
3099    
3100    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
3101        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3102        LSCPResultSet result;
3103    #if HAVE_SQLITE3
3104        try {
3105            String list;
3106            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
3107    
3108            for (int i = 0; i < instrs->size(); i++) {
3109                if (list != "") list += ",";
3110                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
3111            }
3112    
3113            result.Add(list);
3114        } catch (Exception e) {
3115             result.Error(e);
3116        }
3117    #else
3118        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3119    #endif
3120        return result.Produce();
3121    }
3122    
3123    String LSCPServer::GetDbInstrumentInfo(String Instr) {
3124        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
3125        LSCPResultSet result;
3126    #if HAVE_SQLITE3
3127        try {
3128            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
3129    
3130            result.Add("INSTRUMENT_FILE", info.InstrFile);
3131            result.Add("INSTRUMENT_NR", info.InstrNr);
3132            result.Add("FORMAT_FAMILY", info.FormatFamily);
3133            result.Add("FORMAT_VERSION", info.FormatVersion);
3134            result.Add("SIZE", (int)info.Size);
3135            result.Add("CREATED", info.Created);
3136            result.Add("MODIFIED", info.Modified);
3137            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3138            result.Add("IS_DRUM", info.IsDrum);
3139            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3140            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3141            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3142        } catch (Exception e) {
3143             result.Error(e);
3144        }
3145    #else
3146        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3147    #endif
3148        return result.Produce();
3149    }
3150    
3151    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3152        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3153        LSCPResultSet result;
3154    #if HAVE_SQLITE3
3155        try {
3156            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3157    
3158            result.Add("FILES_TOTAL", job.FilesTotal);
3159            result.Add("FILES_SCANNED", job.FilesScanned);
3160            result.Add("SCANNING", job.Scanning);
3161            result.Add("STATUS", job.Status);
3162        } catch (Exception e) {
3163             result.Error(e);
3164        }
3165    #else
3166        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3167    #endif
3168        return result.Produce();
3169    }
3170    
3171    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3172        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3173        LSCPResultSet result;
3174    #if HAVE_SQLITE3
3175        try {
3176            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3177        } catch (Exception e) {
3178             result.Error(e);
3179        }
3180    #else
3181        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3182    #endif
3183        return result.Produce();
3184    }
3185    
3186    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3187        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3188        LSCPResultSet result;
3189    #if HAVE_SQLITE3
3190        try {
3191            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3192        } catch (Exception e) {
3193             result.Error(e);
3194        }
3195    #else
3196        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3197    #endif
3198        return result.Produce();
3199    }
3200    
3201    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3202        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3203        LSCPResultSet result;
3204    #if HAVE_SQLITE3
3205        try {
3206            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3207        } catch (Exception e) {
3208             result.Error(e);
3209        }
3210    #else
3211        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3212    #endif
3213        return result.Produce();
3214    }
3215    
3216    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3217        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3218        LSCPResultSet result;
3219    #if HAVE_SQLITE3
3220        try {
3221            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3222        } catch (Exception e) {
3223             result.Error(e);
3224        }
3225    #else
3226        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3227    #endif
3228        return result.Produce();
3229    }
3230    
3231    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3232        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3233        LSCPResultSet result;
3234    #if HAVE_SQLITE3
3235        try {
3236            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3237        } catch (Exception e) {
3238             result.Error(e);
3239        }
3240    #else
3241        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3242    #endif
3243        return result.Produce();
3244    }
3245    
3246    String LSCPServer::FindLostDbInstrumentFiles() {
3247        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3248        LSCPResultSet result;
3249    #if HAVE_SQLITE3
3250        try {
3251            String list;
3252            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3253    
3254            for (int i = 0; i < pLostFiles->size(); i++) {
3255                if (list != "") list += ",";
3256                list += "'" + pLostFiles->at(i) + "'";
3257            }
3258    
3259            result.Add(list);
3260        } catch (Exception e) {
3261             result.Error(e);
3262        }
3263    #else
3264        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3265    #endif
3266        return result.Produce();
3267    }
3268    
3269    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3270        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3271        LSCPResultSet result;
3272    #if HAVE_SQLITE3
3273        try {
3274            SearchQuery Query;
3275            std::map<String,String>::iterator iter;
3276            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3277                if (iter->first.compare("NAME") == 0) {
3278                    Query.Name = iter->second;
3279                } else if (iter->first.compare("CREATED") == 0) {
3280                    Query.SetCreated(iter->second);
3281                } else if (iter->first.compare("MODIFIED") == 0) {
3282                    Query.SetModified(iter->second);
3283                } else if (iter->first.compare("DESCRIPTION") == 0) {
3284                    Query.Description = iter->second;
3285                } else {
3286                    throw Exception("Unknown search criteria: " + iter->first);
3287                }
3288            }
3289    
3290            String list;
3291            StringListPtr pDirectories =
3292                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3293    
3294            for (int i = 0; i < pDirectories->size(); i++) {
3295                if (list != "") list += ",";
3296                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3297            }
3298    
3299            result.Add(list);
3300        } catch (Exception e) {
3301             result.Error(e);
3302        }
3303    #else
3304        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3305    #endif
3306        return result.Produce();
3307    }
3308    
3309    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3310        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3311        LSCPResultSet result;
3312    #if HAVE_SQLITE3
3313        try {
3314            SearchQuery Query;
3315            std::map<String,String>::iterator iter;
3316            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3317                if (iter->first.compare("NAME") == 0) {
3318                    Query.Name = iter->second;
3319                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3320                    Query.SetFormatFamilies(iter->second);
3321                } else if (iter->first.compare("SIZE") == 0) {
3322                    Query.SetSize(iter->second);
3323                } else if (iter->first.compare("CREATED") == 0) {
3324                    Query.SetCreated(iter->second);
3325                } else if (iter->first.compare("MODIFIED") == 0) {
3326                    Query.SetModified(iter->second);
3327                } else if (iter->first.compare("DESCRIPTION") == 0) {
3328                    Query.Description = iter->second;
3329                } else if (iter->first.compare("IS_DRUM") == 0) {
3330                    if (!strcasecmp(iter->second.c_str(), "true")) {
3331                        Query.InstrType = SearchQuery::DRUM;
3332                    } else {
3333                        Query.InstrType = SearchQuery::CHROMATIC;
3334                    }
3335                } else if (iter->first.compare("PRODUCT") == 0) {
3336                     Query.Product = iter->second;
3337                } else if (iter->first.compare("ARTISTS") == 0) {
3338                     Query.Artists = iter->second;
3339                } else if (iter->first.compare("KEYWORDS") == 0) {
3340                     Query.Keywords = iter->second;
3341                } else {
3342                    throw Exception("Unknown search criteria: " + iter->first);
3343                }
3344            }
3345    
3346            String list;
3347            StringListPtr pInstruments =
3348                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3349    
3350            for (int i = 0; i < pInstruments->size(); i++) {
3351                if (list != "") list += ",";
3352                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3353            }
3354    
3355            result.Add(list);
3356        } catch (Exception e) {
3357             result.Error(e);
3358        }
3359    #else
3360        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3361    #endif
3362        return result.Produce();
3363    }
3364    
3365    String LSCPServer::FormatInstrumentsDb() {
3366        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3367        LSCPResultSet result;
3368    #if HAVE_SQLITE3
3369        try {
3370            InstrumentsDb::GetInstrumentsDb()->Format();
3371        } catch (Exception e) {
3372             result.Error(e);
3373        }
3374    #else
3375        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3376    #endif
3377        return result.Produce();
3378    }
3379    
3380    
3381  /**  /**
3382   * 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
3383   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be
# Line 2301  String LSCPServer::SetEcho(yyparse_param Line 3396  String LSCPServer::SetEcho(yyparse_param
3396      }      }
3397      return result.Produce();      return result.Produce();
3398  }  }
3399    
3400    }

Legend:
Removed from v.1133  
changed lines
  Added in v.2025

  ViewVC Help
Powered by ViewVC