/[svn]/linuxsampler/trunk/src/network/lscpserver.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/network/lscpserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1350 by iliev, Sun Sep 16 23:06:10 2007 UTC revision 2138 by schoenebeck, Mon Oct 4 22:11:53 2010 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 - 2010 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    #include <string>
26    
27    #include "../common/File.h"
28  #include "lscpserver.h"  #include "lscpserver.h"
29  #include "lscpresultset.h"  #include "lscpresultset.h"
30  #include "lscpevent.h"  #include "lscpevent.h"
31    
32    #if defined(WIN32)
33    #include <windows.h>
34    #else
35  #include <fcntl.h>  #include <fcntl.h>
36    #endif
37    
38  #if ! HAVE_SQLITE3  #if ! HAVE_SQLITE3
39  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
# Line 35  Line 43 
43  #include "../engines/EngineChannelFactory.h"  #include "../engines/EngineChannelFactory.h"
44  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
45  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
46    #include "../effects/EffectFactory.h"
47    
48    namespace LinuxSampler {
49    
50    /**
51     * Returns a copy of the given string where all special characters are
52     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
53     * to escape LSCP response fields in case the respective response field is
54     * actually defined as using escape sequences in the LSCP specs.
55     *
56     * @e Caution: DO NOT use this function for escaping path based responses,
57     * use the Path class (src/common/Path.h) for this instead!
58     */
59    static String _escapeLscpResponse(String txt) {
60        for (int i = 0; i < txt.length(); i++) {
61            const char c = txt.c_str()[i];
62            if (
63                !(c >= '0' && c <= '9') &&
64                !(c >= 'a' && c <= 'z') &&
65                !(c >= 'A' && c <= 'Z') &&
66                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
67                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
68                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
69                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
70                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
71                !(c == '@') && !(c == '[') && !(c == ']') &&
72                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
73                !(c == '|') && !(c == '}') && !(c == '~')
74            ) {
75                // convert the "special" character into a "\xHH" LSCP escape sequence
76                char buf[5];
77                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
78                txt.replace(i, 1, buf);
79                i += 3;
80            }
81        }
82        return txt;
83    }
84    
85  /**  /**
86   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
# Line 61  Mutex LSCPServer::NotifyBufferMutex = Mu Line 107  Mutex LSCPServer::NotifyBufferMutex = Mu
107  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
108  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
109    
110  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) {
111      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
112      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
113      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 87  LSCPServer::LSCPServer(Sampler* pSampler Line 133  LSCPServer::LSCPServer(Sampler* pSampler
133      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
134      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
135      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
136        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
137      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
138      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
139        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
140        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
141      hSocket = -1;      hSocket = -1;
142  }  }
143    
144  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
145        CloseAllConnections();
146        InstrumentManager::StopBackgroundThread();
147    #if defined(WIN32)
148        if (hSocket >= 0) closesocket(hSocket);
149    #else
150      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
151    #endif
152    }
153    
154    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
155        this->pParent = pParent;
156    }
157    
158    LSCPServer::EventHandler::~EventHandler() {
159        std::vector<midi_listener_entry> l = channelMidiListeners;
160        channelMidiListeners.clear();
161        for (int i = 0; i < l.size(); i++)
162            delete l[i].pMidiListener;
163  }  }
164    
165  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
166      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
167  }  }
168    
169    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
170        pChannel->AddEngineChangeListener(this);
171    }
172    
173    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
174        if (!pChannel->GetEngineChannel()) return;
175        EngineToBeChanged(pChannel->Index());
176    }
177    
178    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
179        SamplerChannel* pSamplerChannel =
180            pParent->pSampler->GetSamplerChannel(ChannelId);
181        if (!pSamplerChannel) return;
182        EngineChannel* pEngineChannel =
183            pSamplerChannel->GetEngineChannel();
184        if (!pEngineChannel) return;
185        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
186            if ((*iter).pEngineChannel == pEngineChannel) {
187                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
188                pEngineChannel->Disconnect(pMidiListener);
189                channelMidiListeners.erase(iter);
190                delete pMidiListener;
191                return;
192            }
193        }
194    }
195    
196    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
197        SamplerChannel* pSamplerChannel =
198            pParent->pSampler->GetSamplerChannel(ChannelId);
199        if (!pSamplerChannel) return;
200        EngineChannel* pEngineChannel =
201            pSamplerChannel->GetEngineChannel();
202        if (!pEngineChannel) return;
203        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
204        pEngineChannel->Connect(pMidiListener);
205        midi_listener_entry entry = {
206            pSamplerChannel, pEngineChannel, pMidiListener
207        };
208        channelMidiListeners.push_back(entry);
209    }
210    
211  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
212      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
213  }  }
# Line 108  void LSCPServer::EventHandler::MidiDevic Line 216  void LSCPServer::EventHandler::MidiDevic
216      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
217  }  }
218    
219    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
220        pDevice->RemoveMidiPortCountListener(this);
221        for (int i = 0; i < pDevice->PortCount(); ++i)
222            MidiPortToBeRemoved(pDevice->GetPort(i));
223    }
224    
225    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
226        pDevice->AddMidiPortCountListener(this);
227        for (int i = 0; i < pDevice->PortCount(); ++i)
228            MidiPortAdded(pDevice->GetPort(i));
229    }
230    
231    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
232        // yet unused
233    }
234    
235    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
236        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
237            if ((*iter).pPort == pPort) {
238                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
239                pPort->Disconnect(pMidiListener);
240                deviceMidiListeners.erase(iter);
241                delete pMidiListener;
242                return;
243            }
244        }
245    }
246    
247    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
248        // find out the device ID
249        std::map<uint, MidiInputDevice*> devices =
250            pParent->pSampler->GetMidiInputDevices();
251        for (
252            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
253            iter != devices.end(); ++iter
254        ) {
255            if (iter->second == pPort->GetDevice()) { // found
256                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
257                pPort->Connect(pMidiListener);
258                device_midi_listener_entry entry = {
259                    pPort, pMidiListener, iter->first
260                };
261                deviceMidiListeners.push_back(entry);
262                return;
263            }
264        }
265    }
266    
267  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
268      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
269  }  }
# Line 144  void LSCPServer::EventHandler::TotalVoic Line 300  void LSCPServer::EventHandler::TotalVoic
300      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
301  }  }
302    
303    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
304        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
305    }
306    
307  #if HAVE_SQLITE3  #if HAVE_SQLITE3
308  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
309      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
# Line 178  void LSCPServer::DbInstrumentsEventHandl Line 338  void LSCPServer::DbInstrumentsEventHandl
338  }  }
339  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
340    
341    void LSCPServer::RemoveListeners() {
342        pSampler->RemoveChannelCountListener(&eventHandler);
343        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
344        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
345        pSampler->RemoveVoiceCountListener(&eventHandler);
346        pSampler->RemoveStreamCountListener(&eventHandler);
347        pSampler->RemoveBufferFillListener(&eventHandler);
348        pSampler->RemoveTotalStreamCountListener(&eventHandler);
349        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
350        pSampler->RemoveFxSendCountListener(&eventHandler);
351        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
352        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
353        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
354        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
355    #if HAVE_SQLITE3
356        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
357    #endif
358    }
359    
360  /**  /**
361   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 194  int LSCPServer::WaitUntilInitialized(lon Line 372  int LSCPServer::WaitUntilInitialized(lon
372  }  }
373    
374  int LSCPServer::Main() {  int LSCPServer::Main() {
375            #if defined(WIN32)
376            WSADATA wsaData;
377            int iResult;
378            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
379            if (iResult != 0) {
380                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
381                    exit(EXIT_FAILURE);
382            }
383            #endif
384      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
385      if (hSocket < 0) {      if (hSocket < 0) {
386          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 207  int LSCPServer::Main() { Line 394  int LSCPServer::Main() {
394              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
395                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
396                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
397                        #if defined(WIN32)
398                        closesocket(hSocket);
399                        #else
400                      close(hSocket);                      close(hSocket);
401                        #endif
402                      //return -1;                      //return -1;
403                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
404                  }                  }
# Line 227  int LSCPServer::Main() { Line 418  int LSCPServer::Main() {
418      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
419      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
420      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
421        pSampler->AddTotalStreamCountListener(&eventHandler);
422      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
423      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
424      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
# Line 246  int LSCPServer::Main() { Line 438  int LSCPServer::Main() {
438      timeval timeout;      timeval timeout;
439    
440      while (true) {      while (true) {
441            #if CONFIG_PTHREAD_TESTCANCEL
442                    TestCancel();
443            #endif
444          // 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
445          {          {
446              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 253  int LSCPServer::Main() { Line 448  int LSCPServer::Main() {
448              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
449              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
450                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
451                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
452                  }                  }
453    
454                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
455                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
456                      if(fxs != NULL && fxs->IsInfoChanged()) {                      if(fxs != NULL && fxs->IsInfoChanged()) {
457                          int chn = (*itEngineChannel)->iSamplerChannelIndex;                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
458                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
459                          fxs->SetInfoChanged(false);                          fxs->SetInfoChanged(false);
460                      }                      }
# Line 267  int LSCPServer::Main() { Line 462  int LSCPServer::Main() {
462              }              }
463          }          }
464    
465            // check if MIDI data arrived on some engine channel
466            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
467                const EventHandler::midi_listener_entry entry =
468                    eventHandler.channelMidiListeners[i];
469                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
470                if (pMidiListener->NotesChanged()) {
471                    for (int iNote = 0; iNote < 128; iNote++) {
472                        if (pMidiListener->NoteChanged(iNote)) {
473                            const bool bActive = pMidiListener->NoteIsActive(iNote);
474                            LSCPServer::SendLSCPNotify(
475                                LSCPEvent(
476                                    LSCPEvent::event_channel_midi,
477                                    entry.pSamplerChannel->Index(),
478                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
479                                    iNote,
480                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
481                                            : pMidiListener->NoteOffVelocity(iNote)
482                                )
483                            );
484                        }
485                    }
486                }
487            }
488    
489            // check if MIDI data arrived on some MIDI device
490            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
491                const EventHandler::device_midi_listener_entry entry =
492                    eventHandler.deviceMidiListeners[i];
493                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
494                if (pMidiListener->NotesChanged()) {
495                    for (int iNote = 0; iNote < 128; iNote++) {
496                        if (pMidiListener->NoteChanged(iNote)) {
497                            const bool bActive = pMidiListener->NoteIsActive(iNote);
498                            LSCPServer::SendLSCPNotify(
499                                LSCPEvent(
500                                    LSCPEvent::event_device_midi,
501                                    entry.uiDeviceID,
502                                    entry.pPort->GetPortNumber(),
503                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
504                                    iNote,
505                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
506                                            : pMidiListener->NoteOffVelocity(iNote)
507                                )
508                            );
509                        }
510                    }
511                }
512            }
513    
514          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
515          NotifyBufferMutex.Lock();          NotifyBufferMutex.Lock();
516          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 285  int LSCPServer::Main() { Line 529  int LSCPServer::Main() {
529    
530          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
531    
532          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
533                  continue; //Nothing try again                  continue; //Nothing try again
534          if (retval == -1) {          if (retval == -1) {
535                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
536                    #if defined(WIN32)
537                    closesocket(hSocket);
538                    #else
539                  close(hSocket);                  close(hSocket);
540                    #endif
541                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
542          }          }
543    
# Line 301  int LSCPServer::Main() { Line 549  int LSCPServer::Main() {
549                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
550                  }                  }
551    
552                    #if defined(WIN32)
553                    u_long nonblock_io = 1;
554                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
555                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
556                      exit(EXIT_FAILURE);
557                    }
558            #else
559                    struct linger linger;
560                    linger.l_onoff = 1;
561                    linger.l_linger = 0;
562                    if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) {
563                        std::cerr << "LSCPServer: Failed to set SO_LINGER\n";
564                    }
565    
566                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
567                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
568                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
569                  }                  }
570                    #endif
571    
572                  // Parser initialization                  // Parser initialization
573                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 363  void LSCPServer::CloseConnection( std::v Line 626  void LSCPServer::CloseConnection( std::v
626          NotifyMutex.Lock();          NotifyMutex.Lock();
627          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
628          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
629            #if defined(WIN32)
630            closesocket(socket);
631            #else
632          close(socket);          close(socket);
633            #endif
634          NotifyMutex.Unlock();          NotifyMutex.Unlock();
635  }  }
636    
637    void LSCPServer::CloseAllConnections() {
638        std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
639        while(iter != Sessions.end()) {
640            CloseConnection(iter);
641            iter = Sessions.begin();
642        }
643    }
644    
645    void LSCPServer::LockRTNotify() {
646        RTNotifyMutex.Lock();
647    }
648    
649    void LSCPServer::UnlockRTNotify() {
650        RTNotifyMutex.Unlock();
651    }
652    
653  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
654          int subs = 0;          int subs = 0;
655          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 442  bool LSCPServer::GetLSCPCommand( std::ve Line 725  bool LSCPServer::GetLSCPCommand( std::ve
725          char c;          char c;
726          int i = 0;          int i = 0;
727          while (true) {          while (true) {
728                    #if defined(WIN32)
729                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
730                    #else
731                  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
732                    #endif
733                  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
734                          CloseConnection(iter);                          CloseConnection(iter);
735                          break;                          break;
# Line 457  bool LSCPServer::GetLSCPCommand( std::ve Line 744  bool LSCPServer::GetLSCPCommand( std::ve
744                          }                          }
745                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
746                  }                  }
747                    #if defined(WIN32)
748                    if (result == SOCKET_ERROR) {
749                        int wsa_lasterror = WSAGetLastError();
750                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
751                                    return false;
752                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
753                            CloseConnection(iter);
754                            break;
755                    }
756                    #else
757                  if (result == -1) {                  if (result == -1) {
758                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
759                                  return false;                                  return false;
# Line 495  bool LSCPServer::GetLSCPCommand( std::ve Line 792  bool LSCPServer::GetLSCPCommand( std::ve
792                          CloseConnection(iter);                          CloseConnection(iter);
793                          break;                          break;
794                  }                  }
795                    #endif
796          }          }
797          return false;          return false;
798  }  }
# Line 768  String LSCPServer::GetEngineInfo(String Line 1066  String LSCPServer::GetEngineInfo(String
1066      LockRTNotify();      LockRTNotify();
1067      try {      try {
1068          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1069          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1070          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1071          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1072      }      }
# Line 841  String LSCPServer::GetChannelInfo(uint u Line 1139  String LSCPServer::GetChannelInfo(uint u
1139          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1140          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1141    
1142            // convert the filename into the correct encoding as defined for LSCP
1143            // (especially in terms of special characters -> escape sequences)
1144            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1145    #if WIN32
1146                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1147    #else
1148                // assuming POSIX
1149                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1150    #endif
1151            }
1152    
1153          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1154          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1155          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1156          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1157          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1158          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 863  String LSCPServer::GetVoiceCount(uint ui Line 1172  String LSCPServer::GetVoiceCount(uint ui
1172      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1173      LSCPResultSet result;      LSCPResultSet result;
1174      try {      try {
1175          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine loaded on sampler channel");  
1176          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1177          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1178      }      }
# Line 884  String LSCPServer::GetStreamCount(uint u Line 1190  String LSCPServer::GetStreamCount(uint u
1190      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1191      LSCPResultSet result;      LSCPResultSet result;
1192      try {      try {
1193          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1194          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1195          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1196      }      }
# Line 905  String LSCPServer::GetBufferFill(fill_re Line 1208  String LSCPServer::GetBufferFill(fill_re
1208      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1209      LSCPResultSet result;      LSCPResultSet result;
1210      try {      try {
1211          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");  
1212          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");
1213          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1214          else {          else {
# Line 996  String LSCPServer::GetMidiInputDriverInf Line 1296  String LSCPServer::GetMidiInputDriverInf
1296              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1297                  if (s != "") s += ",";                  if (s != "") s += ",";
1298                  s += iter->first;                  s += iter->first;
1299                    delete iter->second;
1300              }              }
1301              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1302          }          }
# Line 1020  String LSCPServer::GetAudioOutputDriverI Line 1321  String LSCPServer::GetAudioOutputDriverI
1321              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1322                  if (s != "") s += ",";                  if (s != "") s += ",";
1323                  s += iter->first;                  s += iter->first;
1324                    delete iter->second;
1325              }              }
1326              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1327          }          }
# Line 1050  String LSCPServer::GetMidiInputDriverPar Line 1352  String LSCPServer::GetMidiInputDriverPar
1352          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1353          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1354          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1355            delete pParameter;
1356      }      }
1357      catch (Exception e) {      catch (Exception e) {
1358          result.Error(e);          result.Error(e);
# Line 1077  String LSCPServer::GetAudioOutputDriverP Line 1380  String LSCPServer::GetAudioOutputDriverP
1380          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1381          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1382          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1383            delete pParameter;
1384      }      }
1385      catch (Exception e) {      catch (Exception e) {
1386          result.Error(e);          result.Error(e);
# Line 1543  String LSCPServer::SetMIDIInputType(Stri Line 1847  String LSCPServer::SetMIDIInputType(Stri
1847              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1848              // Make it with at least one initial port.              // Make it with at least one initial port.
1849              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
             parameters["PORTS"]->SetValue("1");  
1850          }          }
1851          // Must have a device...          // Must have a device...
1852          if (pDevice == NULL)          if (pDevice == NULL)
# Line 1586  String LSCPServer::SetVolume(double dVol Line 1889  String LSCPServer::SetVolume(double dVol
1889      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1890      LSCPResultSet result;      LSCPResultSet result;
1891      try {      try {
1892          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");  
1893          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
1894      }      }
1895      catch (Exception e) {      catch (Exception e) {
# Line 1605  String LSCPServer::SetChannelMute(bool b Line 1905  String LSCPServer::SetChannelMute(bool b
1905      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1906      LSCPResultSet result;      LSCPResultSet result;
1907      try {      try {
1908          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1909    
1910          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1911          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1626  String LSCPServer::SetChannelSolo(bool b Line 1922  String LSCPServer::SetChannelSolo(bool b
1922      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1923      LSCPResultSet result;      LSCPResultSet result;
1924      try {      try {
1925          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");  
1926    
1927          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1928          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
# Line 1750  String LSCPServer::GetMidiInstrumentMapp Line 2042  String LSCPServer::GetMidiInstrumentMapp
2042      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2043      LSCPResultSet result;      LSCPResultSet result;
2044      try {      try {
2045          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2046      } catch (Exception e) {      } catch (Exception e) {
2047          result.Error(e);          result.Error(e);
2048      }      }
# Line 1761  String LSCPServer::GetMidiInstrumentMapp Line 2053  String LSCPServer::GetMidiInstrumentMapp
2053  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2054      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2055      LSCPResultSet result;      LSCPResultSet result;
2056      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2057      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2058      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2059          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2060      }      }
     result.Add(totalMappings);  
2061      return result.Produce();      return result.Produce();
2062  }  }
2063    
# Line 1776  String LSCPServer::GetMidiInstrumentMapp Line 2065  String LSCPServer::GetMidiInstrumentMapp
2065      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2066      LSCPResultSet result;      LSCPResultSet result;
2067      try {      try {
2068          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2069          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2070          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
2071          idx.midi_prog     = MidiProg;  #if WIN32
2072            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2073          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);  #else
2074          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          // assuming POSIX
2075          if (iter == mappings.end()) result.Error("there is no map entry with that index");          const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2076          else { // found  #endif
2077              result.Add("NAME", iter->second.Name);  
2078              result.Add("ENGINE_NAME", iter->second.EngineName);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2079              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          result.Add("ENGINE_NAME", entry.EngineName);
2080              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);          result.Add("INSTRUMENT_FILE", instrumentFileName);
2081              String instrumentName;          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2082              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);          String instrumentName;
2083              if (pEngine) {          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2084                  if (pEngine->GetInstrumentManager()) {          if (pEngine) {
2085                      InstrumentManager::instrument_id_t instrID;              if (pEngine->GetInstrumentManager()) {
2086                      instrID.FileName = iter->second.InstrumentFile;                  InstrumentManager::instrument_id_t instrID;
2087                      instrID.Index    = iter->second.InstrumentIndex;                  instrID.FileName = entry.InstrumentFile;
2088                      instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);                  instrID.Index    = entry.InstrumentIndex;
2089                  }                  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!");  
2090              }              }
2091              result.Add("VOLUME", iter->second.Volume);              EngineFactory::Destroy(pEngine);
2092          }          }
2093            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2094            switch (entry.LoadMode) {
2095                case MidiInstrumentMapper::ON_DEMAND:
2096                    result.Add("LOAD_MODE", "ON_DEMAND");
2097                    break;
2098                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2099                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2100                    break;
2101                case MidiInstrumentMapper::PERSISTENT:
2102                    result.Add("LOAD_MODE", "PERSISTENT");
2103                    break;
2104                default:
2105                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2106            }
2107            result.Add("VOLUME", entry.Volume);
2108      } catch (Exception e) {      } catch (Exception e) {
2109          result.Error(e);          result.Error(e);
2110      }      }
# Line 1955  String LSCPServer::GetMidiInstrumentMap( Line 2244  String LSCPServer::GetMidiInstrumentMap(
2244      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2245      LSCPResultSet result;      LSCPResultSet result;
2246      try {      try {
2247          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2248          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2249      } catch (Exception e) {      } catch (Exception e) {
2250          result.Error(e);          result.Error(e);
# Line 1986  String LSCPServer::SetChannelMap(uint ui Line 2275  String LSCPServer::SetChannelMap(uint ui
2275      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2276      LSCPResultSet result;      LSCPResultSet result;
2277      try {      try {
2278          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");  
2279    
2280          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2281          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 2098  String LSCPServer::GetFxSendInfo(uint ui Line 2383  String LSCPServer::GetFxSendInfo(uint ui
2383              AudioRouting += ToString(pFxSend->DestinationChannel(chan));              AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2384          }          }
2385    
2386            const String sEffectRouting =
2387                (pFxSend->DestinationEffectChain() >= 0 && pFxSend->DestinationEffectChainPosition() >= 0)
2388                    ? ToString(pFxSend->DestinationEffectChain()) + "," + ToString(pFxSend->DestinationEffectChainPosition())
2389                    : "NONE";
2390    
2391          // success          // success
2392          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2393          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2394          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2395          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2396            result.Add("SEND_EFFECT", sEffectRouting);
2397      } catch (Exception e) {      } catch (Exception e) {
2398          result.Error(e);          result.Error(e);
2399      }      }
# Line 2165  String LSCPServer::SetFxSendLevel(uint u Line 2456  String LSCPServer::SetFxSendLevel(uint u
2456      return result.Produce();      return result.Produce();
2457  }  }
2458    
2459    String LSCPServer::SetFxSendEffect(uint uiSamplerChannel, uint FxSendID, int iSendEffectChain, int iEffectChainPosition) {
2460        dmsg(2,("LSCPServer: SetFxSendEffect(%d,%d)\n", iSendEffectChain, iEffectChainPosition));
2461        LSCPResultSet result;
2462        try {
2463            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2464    
2465            pFxSend->SetDestinationEffect(iSendEffectChain, iEffectChainPosition);
2466            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2467        } catch (Exception e) {
2468            result.Error(e);
2469        }
2470        return result.Produce();
2471    }
2472    
2473    String LSCPServer::GetAvailableEffects() {
2474        dmsg(2,("LSCPServer: GetAvailableEffects()\n"));
2475        LSCPResultSet result;
2476        try {
2477            int n = EffectFactory::AvailableEffectsCount();
2478            result.Add(n);
2479        }
2480        catch (Exception e) {
2481            result.Error(e);
2482        }
2483        return result.Produce();
2484    }
2485    
2486    String LSCPServer::ListAvailableEffects() {
2487        dmsg(2,("LSCPServer: ListAvailableEffects()\n"));
2488        LSCPResultSet result;
2489        String list;
2490        try {
2491            //FIXME: for now we simply enumerate from 0 .. EffectFactory::AvailableEffectsCount() here, in future we should use unique IDs for effects during the whole sampler session. This issue comes into game when the user forces a reload of available effect plugins
2492            int n = EffectFactory::AvailableEffectsCount();
2493            for (int i = 0; i < n; i++) {
2494                if (i) list += ",";
2495                list += ToString(i);
2496            }
2497        }
2498        catch (Exception e) {
2499            result.Error(e);
2500        }
2501        result.Add(list);
2502        return result.Produce();
2503    }
2504    
2505    String LSCPServer::GetEffectInfo(int iEffectIndex) {
2506        dmsg(2,("LSCPServer: GetEffectInfo(%d)\n", iEffectIndex));
2507        LSCPResultSet result;
2508        try {
2509            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2510            if (!pEffectInfo)
2511                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2512    
2513            // convert the filename into the correct encoding as defined for LSCP
2514            // (especially in terms of special characters -> escape sequences)
2515    #if WIN32
2516            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2517    #else
2518            // assuming POSIX
2519            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2520    #endif
2521    
2522            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2523            result.Add("MODULE", dllFileName);
2524            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2525            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2526        }
2527        catch (Exception e) {
2528            result.Error(e);
2529        }
2530        return result.Produce();    
2531    }
2532    
2533    String LSCPServer::GetEffectInstanceInfo(int iEffectInstance) {
2534        dmsg(2,("LSCPServer: GetEffectInstanceInfo(%d)\n", iEffectInstance));
2535        LSCPResultSet result;
2536        try {
2537            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2538            if (!pEffect)
2539                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2540    
2541            EffectInfo* pEffectInfo = pEffect->GetEffectInfo();
2542    
2543            // convert the filename into the correct encoding as defined for LSCP
2544            // (especially in terms of special characters -> escape sequences)
2545    #if WIN32
2546            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2547    #else
2548            // assuming POSIX
2549            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2550    #endif
2551    
2552            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2553            result.Add("MODULE", dllFileName);
2554            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2555            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2556            result.Add("INPUT_CONTROLS", ToString(pEffect->InputControlCount()));
2557        }
2558        catch (Exception e) {
2559            result.Error(e);
2560        }
2561        return result.Produce();
2562    }
2563    
2564    String LSCPServer::GetEffectInstanceInputControlInfo(int iEffectInstance, int iInputControlIndex) {
2565        dmsg(2,("LSCPServer: GetEffectInstanceInputControlInfo(%d,%d)\n", iEffectInstance, iInputControlIndex));
2566        LSCPResultSet result;
2567        try {
2568            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2569            if (!pEffect)
2570                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2571    
2572            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2573            if (!pEffectControl)
2574                throw Exception(
2575                    "Effect instance " + ToString(iEffectInstance) +
2576                    " does not have an input control with index " +
2577                    ToString(iInputControlIndex)
2578                );
2579    
2580            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectControl->Description()));
2581            result.Add("VALUE", pEffectControl->Value());
2582            if (pEffectControl->MinValue())
2583                 result.Add("RANGE_MIN", *pEffectControl->MinValue());
2584            if (pEffectControl->MaxValue())
2585                 result.Add("RANGE_MAX", *pEffectControl->MaxValue());
2586            if (!pEffectControl->Possibilities().empty())
2587                 result.Add("POSSIBILITIES", pEffectControl->Possibilities());
2588            if (pEffectControl->DefaultValue())
2589                 result.Add("DEFAULT", *pEffectControl->DefaultValue());
2590        } catch (Exception e) {
2591            result.Error(e);
2592        }
2593        return result.Produce();
2594    }
2595    
2596    String LSCPServer::SetEffectInstanceInputControlValue(int iEffectInstance, int iInputControlIndex, double dValue) {
2597        dmsg(2,("LSCPServer: SetEffectInstanceInputControlValue(%d,%d,%f)\n", iEffectInstance, iInputControlIndex, dValue));
2598        LSCPResultSet result;
2599        try {
2600            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2601            if (!pEffect)
2602                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2603    
2604            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2605            if (!pEffectControl)
2606                throw Exception(
2607                    "Effect instance " + ToString(iEffectInstance) +
2608                    " does not have an input control with index " +
2609                    ToString(iInputControlIndex)
2610                );
2611    
2612            pEffectControl->SetValue(dValue);
2613        } catch (Exception e) {
2614            result.Error(e);
2615        }
2616        return result.Produce();
2617    }
2618    
2619    String LSCPServer::CreateEffectInstance(int iEffectIndex) {
2620        dmsg(2,("LSCPServer: CreateEffectInstance(%d)\n", iEffectIndex));
2621        LSCPResultSet result;
2622        try {
2623            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2624            if (!pEffectInfo)
2625                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2626            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2627            result = pEffect->ID(); // success
2628        } catch (Exception e) {
2629            result.Error(e);
2630        }
2631        return result.Produce();
2632    }
2633    
2634    String LSCPServer::CreateEffectInstance(String effectSystem, String module, String effectName) {
2635        dmsg(2,("LSCPServer: CreateEffectInstance('%s','%s','%s')\n", effectSystem.c_str(), module.c_str(), effectName.c_str()));
2636        LSCPResultSet result;
2637        try {
2638            // to allow loading the same LSCP session file on different systems
2639            // successfully, probably with different effect plugin DLL paths or even
2640            // running completely different operating systems, we do the following
2641            // for finding the right effect:
2642            //
2643            // first try to search for an exact match of the effect plugin DLL
2644            // (a.k.a 'module'), to avoid picking the wrong DLL with the same
2645            // effect name ...
2646            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_MATCH_EXACTLY);
2647            // ... if no effect with exactly matchin DLL filename was found, then
2648            // try to lower the restrictions of matching the effect plugin DLL
2649            // filename and try again and again ...
2650            if (!pEffectInfo) {
2651                dmsg(2,("no exact module match, trying MODULE_IGNORE_PATH\n"));
2652                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH);
2653            }
2654            if (!pEffectInfo) {
2655                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE\n"));
2656                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE);
2657            }
2658            if (!pEffectInfo) {
2659                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE | MODULE_IGNORE_EXTENSION\n"));
2660                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE | EffectFactory::MODULE_IGNORE_EXTENSION);
2661            }
2662            // ... if there was still no effect found, then completely ignore the
2663            // DLL plugin filename argument and just search for the matching effect
2664            // system type and effect name
2665            if (!pEffectInfo) {
2666                dmsg(2,("no module match, trying MODULE_IGNORE_ALL\n"));
2667                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_ALL);
2668            }
2669            if (!pEffectInfo)
2670                throw Exception("There is no such effect '" + effectSystem + "' '" + module + "' '" + effectName + "'");
2671    
2672            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2673            result = LSCPResultSet(pEffect->ID());
2674        } catch (Exception e) {
2675            result.Error(e);
2676        }
2677        return result.Produce();
2678    }
2679    
2680    String LSCPServer::DestroyEffectInstance(int iEffectInstance) {
2681        dmsg(2,("LSCPServer: DestroyEffectInstance(%d)\n", iEffectInstance));
2682        LSCPResultSet result;
2683        try {
2684            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2685            if (!pEffect)
2686                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2687            EffectFactory::Destroy(pEffect);
2688        } catch (Exception e) {
2689            result.Error(e);
2690        }
2691        return result.Produce();
2692    }
2693    
2694    String LSCPServer::GetEffectInstances() {
2695        dmsg(2,("LSCPServer: GetEffectInstances()\n"));
2696        LSCPResultSet result;
2697        try {
2698            int n = EffectFactory::EffectInstancesCount();
2699            result.Add(n);
2700        } catch (Exception e) {
2701            result.Error(e);
2702        }
2703        return result.Produce();
2704    }
2705    
2706    String LSCPServer::ListEffectInstances() {
2707        dmsg(2,("LSCPServer: ListEffectInstances()\n"));
2708        LSCPResultSet result;
2709        String list;
2710        try {
2711            int n = EffectFactory::EffectInstancesCount();
2712            for (int i = 0; i < n; i++) {
2713                Effect* pEffect = EffectFactory::GetEffectInstance(i);
2714                if (i) list += ",";
2715                list += ToString(pEffect->ID());
2716            }
2717        } catch (Exception e) {
2718            result.Error(e);
2719        }
2720        result.Add(list);
2721        return result.Produce();
2722    }
2723    
2724    String LSCPServer::GetSendEffectChains(int iAudioOutputDevice) {
2725        dmsg(2,("LSCPServer: GetSendEffectChains(%d)\n", iAudioOutputDevice));
2726        LSCPResultSet result;
2727        try {
2728            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2729            if (!devices.count(iAudioOutputDevice))
2730                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2731            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2732            int n = pDevice->SendEffectChainCount();
2733            result.Add(n);
2734        } catch (Exception e) {
2735            result.Error(e);
2736        }
2737        return result.Produce();
2738    }
2739    
2740    String LSCPServer::ListSendEffectChains(int iAudioOutputDevice) {
2741        dmsg(2,("LSCPServer: ListSendEffectChains(%d)\n", iAudioOutputDevice));
2742        LSCPResultSet result;
2743        String list;
2744        try {
2745            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2746            if (!devices.count(iAudioOutputDevice))
2747                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2748            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2749            int n = pDevice->SendEffectChainCount();
2750            for (int i = 0; i < n; i++) {
2751                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2752                if (i) list += ",";
2753                list += ToString(pEffectChain->ID());
2754            }
2755        } catch (Exception e) {
2756            result.Error(e);
2757        }
2758        result.Add(list);
2759        return result.Produce();
2760    }
2761    
2762    String LSCPServer::AddSendEffectChain(int iAudioOutputDevice) {
2763        dmsg(2,("LSCPServer: AddSendEffectChain(%d)\n", iAudioOutputDevice));
2764        LSCPResultSet result;
2765        try {
2766            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2767            if (!devices.count(iAudioOutputDevice))
2768                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2769            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2770            EffectChain* pEffectChain = pDevice->AddSendEffectChain();
2771            result = pEffectChain->ID();
2772        } catch (Exception e) {
2773            result.Error(e);
2774        }
2775        return result.Produce();
2776    }
2777    
2778    String LSCPServer::RemoveSendEffectChain(int iAudioOutputDevice, int iSendEffectChain) {
2779        dmsg(2,("LSCPServer: RemoveSendEffectChain(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
2780        LSCPResultSet result;
2781        try {
2782            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2783            if (!devices.count(iAudioOutputDevice))
2784                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2785            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2786            for (int i = 0; i < pDevice->SendEffectChainCount(); i++) {
2787                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2788                if (pEffectChain->ID() == iSendEffectChain) {
2789                    pDevice->RemoveSendEffectChain(i);
2790                    return result.Produce();
2791                }
2792            }
2793            throw Exception(
2794                "There is no send effect chain with ID " +
2795                ToString(iSendEffectChain) + " for audio output device " +
2796                ToString(iAudioOutputDevice) + "."
2797            );
2798        } catch (Exception e) {
2799            result.Error(e);
2800        }
2801        return result.Produce();
2802    }
2803    
2804    static EffectChain* _getSendEffectChain(Sampler* pSampler, int iAudioOutputDevice, int iSendEffectChain) throw (Exception) {
2805        std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2806        if (!devices.count(iAudioOutputDevice))
2807            throw Exception(
2808                "There is no audio output device with index " +
2809                ToString(iAudioOutputDevice) + "."
2810            );
2811        AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2812        for (int i = 0; i < pDevice->SendEffectChainCount(); i++) {
2813            EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2814            if (pEffectChain->ID() == iSendEffectChain) {
2815                return pEffectChain;
2816            }
2817        }
2818        throw Exception(
2819            "There is no send effect chain with ID " +
2820            ToString(iSendEffectChain) + " for audio output device " +
2821            ToString(iAudioOutputDevice) + "."
2822        );
2823    }
2824    
2825    String LSCPServer::GetSendEffectChainInfo(int iAudioOutputDevice, int iSendEffectChain) {
2826        dmsg(2,("LSCPServer: GetSendEffectChainInfo(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
2827        LSCPResultSet result;
2828        try {
2829            EffectChain* pEffectChain =
2830                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
2831            String sEffectSequence;
2832            for (int i = 0; i < pEffectChain->EffectCount(); i++) {
2833                if (i) sEffectSequence += ",";
2834                sEffectSequence += ToString(pEffectChain->GetEffect(i)->ID());
2835            }
2836            result.Add("EFFECT_COUNT", pEffectChain->EffectCount());
2837            result.Add("EFFECT_SEQUENCE", sEffectSequence);
2838        } catch (Exception e) {
2839            result.Error(e);
2840        }
2841        return result.Produce();
2842    }
2843    
2844    String LSCPServer::AppendSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectInstance) {
2845        dmsg(2,("LSCPServer: AppendSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectInstance));
2846        LSCPResultSet result;
2847        try {
2848            EffectChain* pEffectChain =
2849                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
2850            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2851            if (!pEffect)
2852                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2853            pEffectChain->AppendEffect(pEffect);
2854        } catch (Exception e) {
2855            result.Error(e);
2856        }
2857        return result.Produce();
2858    }
2859    
2860    String LSCPServer::InsertSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition, int iEffectInstance) {
2861        dmsg(2,("LSCPServer: InsertSendEffectChainEffect(%d,%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition, iEffectInstance));
2862        LSCPResultSet result;
2863        try {
2864            EffectChain* pEffectChain =
2865                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
2866            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2867            if (!pEffect)
2868                throw Exception("There is no effect instance with index " + ToString(iEffectInstance));
2869            pEffectChain->InsertEffect(pEffect, iEffectChainPosition);
2870        } catch (Exception e) {
2871            result.Error(e);
2872        }
2873        return result.Produce();
2874    }
2875    
2876    String LSCPServer::RemoveSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition) {
2877        dmsg(2,("LSCPServer: RemoveSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition));
2878        LSCPResultSet result;
2879        try {
2880            EffectChain* pEffectChain =
2881                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
2882            pEffectChain->RemoveEffect(iEffectChainPosition);
2883        } catch (Exception e) {
2884            result.Error(e);
2885        }
2886        return result.Produce();
2887    }
2888    
2889  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2890      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2891      LSCPResultSet result;      LSCPResultSet result;
2892      try {      try {
2893          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");  
2894          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2895          Engine* pEngine = pEngineChannel->GetEngine();          Engine* pEngine = pEngineChannel->GetEngine();
2896          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
# Line 2187  String LSCPServer::EditSamplerChannelIns Line 2905  String LSCPServer::EditSamplerChannelIns
2905      return result.Produce();      return result.Produce();
2906  }  }
2907    
2908    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2909        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2910        LSCPResultSet result;
2911        try {
2912            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2913    
2914            if (Arg1 > 127 || Arg2 > 127) {
2915                throw Exception("Invalid MIDI message");
2916            }
2917    
2918            VirtualMidiDevice* pMidiDevice = NULL;
2919            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2920            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2921                if ((*iter).pEngineChannel == pEngineChannel) {
2922                    pMidiDevice = (*iter).pMidiListener;
2923                    break;
2924                }
2925            }
2926            
2927            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2928    
2929            if (MidiMsg == "NOTE_ON") {
2930                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2931                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2932                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2933            } else if (MidiMsg == "NOTE_OFF") {
2934                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2935                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2936                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2937            } else if (MidiMsg == "CC") {
2938                pMidiDevice->SendCCToDevice(Arg1, Arg2);
2939                bool b = pMidiDevice->SendCCToSampler(Arg1, Arg2);
2940                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2941            } else {
2942                throw Exception("Unknown MIDI message type: " + MidiMsg);
2943            }
2944        } catch (Exception e) {
2945            result.Error(e);
2946        }
2947        return result.Produce();
2948    }
2949    
2950  /**  /**
2951   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2952   */   */
# Line 2194  String LSCPServer::ResetChannel(uint uiS Line 2954  String LSCPServer::ResetChannel(uint uiS
2954      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2955      LSCPResultSet result;      LSCPResultSet result;
2956      try {      try {
2957          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");  
2958          pEngineChannel->Reset();          pEngineChannel->Reset();
2959      }      }
2960      catch (Exception e) {      catch (Exception e) {
# Line 2222  String LSCPServer::ResetSampler() { Line 2979  String LSCPServer::ResetSampler() {
2979   */   */
2980  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2981      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2982        const std::string description =
2983            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2984      LSCPResultSet result;      LSCPResultSet result;
2985      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2986      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2987      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2988  #if HAVE_SQLITE3  #if HAVE_SQLITE3
# Line 2236  String LSCPServer::GetServerInfo() { Line 2995  String LSCPServer::GetServerInfo() {
2995  }  }
2996    
2997  /**  /**
2998     * Will be called by the parser to return the current number of all active streams.
2999     */
3000    String LSCPServer::GetTotalStreamCount() {
3001        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
3002        LSCPResultSet result;
3003        result.Add(pSampler->GetDiskStreamCount());
3004        return result.Produce();
3005    }
3006    
3007    /**
3008   * Will be called by the parser to return the current number of all active voices.   * Will be called by the parser to return the current number of all active voices.
3009   */   */
3010  String LSCPServer::GetTotalVoiceCount() {  String LSCPServer::GetTotalVoiceCount() {
# Line 2251  String LSCPServer::GetTotalVoiceCount() Line 3020  String LSCPServer::GetTotalVoiceCount()
3020  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
3021      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
3022      LSCPResultSet result;      LSCPResultSet result;
3023      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
3024        return result.Produce();
3025    }
3026    
3027    /**
3028     * Will be called by the parser to return the sampler global maximum
3029     * allowed number of voices.
3030     */
3031    String LSCPServer::GetGlobalMaxVoices() {
3032        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
3033        LSCPResultSet result;
3034        result.Add(GLOBAL_MAX_VOICES);
3035        return result.Produce();
3036    }
3037    
3038    /**
3039     * Will be called by the parser to set the sampler global maximum number of
3040     * voices.
3041     */
3042    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
3043        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
3044        LSCPResultSet result;
3045        try {
3046            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
3047            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
3048            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
3049            if (engines.size() > 0) {
3050                std::set<Engine*>::iterator iter = engines.begin();
3051                std::set<Engine*>::iterator end  = engines.end();
3052                for (; iter != end; ++iter) {
3053                    (*iter)->SetMaxVoices(iVoices);
3054                }
3055            }
3056            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
3057        } catch (Exception e) {
3058            result.Error(e);
3059        }
3060        return result.Produce();
3061    }
3062    
3063    /**
3064     * Will be called by the parser to return the sampler global maximum
3065     * allowed number of disk streams.
3066     */
3067    String LSCPServer::GetGlobalMaxStreams() {
3068        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
3069        LSCPResultSet result;
3070        result.Add(GLOBAL_MAX_STREAMS);
3071        return result.Produce();
3072    }
3073    
3074    /**
3075     * Will be called by the parser to set the sampler global maximum number of
3076     * disk streams.
3077     */
3078    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
3079        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
3080        LSCPResultSet result;
3081        try {
3082            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
3083            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
3084            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
3085            if (engines.size() > 0) {
3086                std::set<Engine*>::iterator iter = engines.begin();
3087                std::set<Engine*>::iterator end  = engines.end();
3088                for (; iter != end; ++iter) {
3089                    (*iter)->SetMaxDiskStreams(iStreams);
3090                }
3091            }
3092            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
3093        } catch (Exception e) {
3094            result.Error(e);
3095        }
3096      return result.Produce();      return result.Produce();
3097  }  }
3098    
# Line 2265  String LSCPServer::SetGlobalVolume(doubl Line 3106  String LSCPServer::SetGlobalVolume(doubl
3106      LSCPResultSet result;      LSCPResultSet result;
3107      try {      try {
3108          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
3109          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
3110          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
3111      } catch (Exception e) {      } catch (Exception e) {
3112          result.Error(e);          result.Error(e);
# Line 2273  String LSCPServer::SetGlobalVolume(doubl Line 3114  String LSCPServer::SetGlobalVolume(doubl
3114      return result.Produce();      return result.Produce();
3115  }  }
3116    
3117    String LSCPServer::GetFileInstruments(String Filename) {
3118        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
3119        LSCPResultSet result;
3120        try {
3121            VerifyFile(Filename);
3122        } catch (Exception e) {
3123            result.Error(e);
3124            return result.Produce();
3125        }
3126        // try to find a sampler engine that can handle the file
3127        bool bFound = false;
3128        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
3129        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
3130            Engine* pEngine = NULL;
3131            try {
3132                pEngine = EngineFactory::Create(engineTypes[i]);
3133                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
3134                InstrumentManager* pManager = pEngine->GetInstrumentManager();
3135                if (pManager) {
3136                    std::vector<InstrumentManager::instrument_id_t> IDs =
3137                        pManager->GetInstrumentFileContent(Filename);
3138                    // return the amount of instruments in the file
3139                    result.Add(IDs.size());
3140                    // no more need to ask other engine types
3141                    bFound = true;
3142                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
3143            } catch (Exception e) {
3144                // NOOP, as exception is thrown if engine doesn't support file
3145            }
3146            if (pEngine) EngineFactory::Destroy(pEngine);
3147        }
3148    
3149        if (!bFound) result.Error("Unknown file format");
3150        return result.Produce();
3151    }
3152    
3153    String LSCPServer::ListFileInstruments(String Filename) {
3154        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
3155        LSCPResultSet result;
3156        try {
3157            VerifyFile(Filename);
3158        } catch (Exception e) {
3159            result.Error(e);
3160            return result.Produce();
3161        }
3162        // try to find a sampler engine that can handle the file
3163        bool bFound = false;
3164        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
3165        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
3166            Engine* pEngine = NULL;
3167            try {
3168                pEngine = EngineFactory::Create(engineTypes[i]);
3169                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
3170                InstrumentManager* pManager = pEngine->GetInstrumentManager();
3171                if (pManager) {
3172                    std::vector<InstrumentManager::instrument_id_t> IDs =
3173                        pManager->GetInstrumentFileContent(Filename);
3174                    // return a list of IDs of the instruments in the file
3175                    String s;
3176                    for (int j = 0; j < IDs.size(); j++) {
3177                        if (s.size()) s += ",";
3178                        s += ToString(IDs[j].Index);
3179                    }
3180                    result.Add(s);
3181                    // no more need to ask other engine types
3182                    bFound = true;
3183                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
3184            } catch (Exception e) {
3185                // NOOP, as exception is thrown if engine doesn't support file
3186            }
3187            if (pEngine) EngineFactory::Destroy(pEngine);
3188        }
3189    
3190        if (!bFound) result.Error("Unknown file format");
3191        return result.Produce();
3192    }
3193    
3194    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
3195        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
3196        LSCPResultSet result;
3197        try {
3198            VerifyFile(Filename);
3199        } catch (Exception e) {
3200            result.Error(e);
3201            return result.Produce();
3202        }
3203        InstrumentManager::instrument_id_t id;
3204        id.FileName = Filename;
3205        id.Index    = InstrumentID;
3206        // try to find a sampler engine that can handle the file
3207        bool bFound = false;
3208        bool bFatalErr = false;
3209        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
3210        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
3211            Engine* pEngine = NULL;
3212            try {
3213                pEngine = EngineFactory::Create(engineTypes[i]);
3214                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
3215                InstrumentManager* pManager = pEngine->GetInstrumentManager();
3216                if (pManager) {
3217                    // check if the instrument index is valid
3218                    // FIXME: this won't work if an engine only supports parts of the instrument file
3219                    std::vector<InstrumentManager::instrument_id_t> IDs =
3220                        pManager->GetInstrumentFileContent(Filename);
3221                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
3222                        std::stringstream ss;
3223                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
3224                        bFatalErr = true;
3225                        throw Exception(ss.str());
3226                    }
3227                    // get the info of the requested instrument
3228                    InstrumentManager::instrument_info_t info =
3229                        pManager->GetInstrumentInfo(id);
3230                    // return detailed informations about the file
3231                    result.Add("NAME", info.InstrumentName);
3232                    result.Add("FORMAT_FAMILY", engineTypes[i]);
3233                    result.Add("FORMAT_VERSION", info.FormatVersion);
3234                    result.Add("PRODUCT", info.Product);
3235                    result.Add("ARTISTS", info.Artists);
3236    
3237                    std::stringstream ss;
3238                    bool b = false;
3239                    for (int i = 0; i < 128; i++) {
3240                        if (info.KeyBindings[i]) {
3241                            if (b) ss << ',';
3242                            ss << i; b = true;
3243                        }
3244                    }
3245                    result.Add("KEY_BINDINGS", ss.str());
3246    
3247                    b = false;
3248                    std::stringstream ss2;
3249                    for (int i = 0; i < 128; i++) {
3250                        if (info.KeySwitchBindings[i]) {
3251                            if (b) ss2 << ',';
3252                            ss2 << i; b = true;
3253                        }
3254                    }
3255                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
3256                    // no more need to ask other engine types
3257                    bFound = true;
3258                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
3259            } catch (Exception e) {
3260                // usually NOOP, as exception is thrown if engine doesn't support file
3261                if (bFatalErr) result.Error(e);
3262            }
3263            if (pEngine) EngineFactory::Destroy(pEngine);
3264        }
3265    
3266        if (!bFound && !bFatalErr) result.Error("Unknown file format");
3267        return result.Produce();
3268    }
3269    
3270    void LSCPServer::VerifyFile(String Filename) {
3271        #if WIN32
3272        WIN32_FIND_DATA win32FileAttributeData;
3273        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
3274        if (!res) {
3275            std::stringstream ss;
3276            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
3277            throw Exception(ss.str());
3278        }
3279        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
3280            throw Exception("Directory is specified");
3281        }
3282        #else
3283        File f(Filename);
3284        if(!f.Exist()) throw Exception(f.GetErrorMsg());
3285        if (f.IsDirectory()) throw Exception("Directory is specified");
3286        #endif
3287    }
3288    
3289  /**  /**
3290   * 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
3291   * server for receiving event messages.   * server for receiving event messages.
# Line 2374  String LSCPServer::GetDbInstrumentDirect Line 3387  String LSCPServer::GetDbInstrumentDirect
3387      try {      try {
3388          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
3389    
3390          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3391          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
3392          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
3393      } catch (Exception e) {      } catch (Exception e) {
# Line 2464  String LSCPServer::AddDbInstruments(Stri Line 3477  String LSCPServer::AddDbInstruments(Stri
3477      return result.Produce();      return result.Produce();
3478  }  }
3479    
3480  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3481      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
3482      LSCPResultSet result;      LSCPResultSet result;
3483  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3484      try {      try {
3485          int id;          int id;
3486          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3487          if (ScanMode.compare("RECURSIVE") == 0) {          if (ScanMode.compare("RECURSIVE") == 0) {
3488             id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3489          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3490             id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3491          } else if (ScanMode.compare("FLAT") == 0) {          } else if (ScanMode.compare("FLAT") == 0) {
3492             id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);              id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3493          } else {          } else {
3494              throw Exception("Unknown scan mode: " + ScanMode);              throw Exception("Unknown scan mode: " + ScanMode);
3495          }          }
# Line 2558  String LSCPServer::GetDbInstrumentInfo(S Line 3571  String LSCPServer::GetDbInstrumentInfo(S
3571          result.Add("SIZE", (int)info.Size);          result.Add("SIZE", (int)info.Size);
3572          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
3573          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
3574          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3575          result.Add("IS_DRUM", info.IsDrum);          result.Add("IS_DRUM", info.IsDrum);
3576          result.Add("PRODUCT", InstrumentsDb::toEscapedText(info.Product));          result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3577          result.Add("ARTISTS", InstrumentsDb::toEscapedText(info.Artists));          result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3578          result.Add("KEYWORDS", InstrumentsDb::toEscapedText(info.Keywords));          result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3579      } catch (Exception e) {      } catch (Exception e) {
3580           result.Error(e);           result.Error(e);
3581      }      }
# Line 2652  String LSCPServer::SetDbInstrumentDescri Line 3665  String LSCPServer::SetDbInstrumentDescri
3665      return result.Produce();      return result.Produce();
3666  }  }
3667    
3668    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3669        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3670        LSCPResultSet result;
3671    #if HAVE_SQLITE3
3672        try {
3673            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3674        } catch (Exception e) {
3675             result.Error(e);
3676        }
3677    #else
3678        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3679    #endif
3680        return result.Produce();
3681    }
3682    
3683    String LSCPServer::FindLostDbInstrumentFiles() {
3684        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3685        LSCPResultSet result;
3686    #if HAVE_SQLITE3
3687        try {
3688            String list;
3689            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3690    
3691            for (int i = 0; i < pLostFiles->size(); i++) {
3692                if (list != "") list += ",";
3693                list += "'" + pLostFiles->at(i) + "'";
3694            }
3695    
3696            result.Add(list);
3697        } catch (Exception e) {
3698             result.Error(e);
3699        }
3700    #else
3701        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3702    #endif
3703        return result.Produce();
3704    }
3705    
3706  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3707      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3708      LSCPResultSet result;      LSCPResultSet result;
# Line 2748  String LSCPServer::FindDbInstruments(Str Line 3799  String LSCPServer::FindDbInstruments(Str
3799      return result.Produce();      return result.Produce();
3800  }  }
3801    
3802    String LSCPServer::FormatInstrumentsDb() {
3803        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3804        LSCPResultSet result;
3805    #if HAVE_SQLITE3
3806        try {
3807            InstrumentsDb::GetInstrumentsDb()->Format();
3808        } catch (Exception e) {
3809             result.Error(e);
3810        }
3811    #else
3812        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3813    #endif
3814        return result.Produce();
3815    }
3816    
3817    
3818  /**  /**
3819   * Will be called by the parser to enable or disable echo mode; if echo   * Will be called by the parser to enable or disable echo mode; if echo
# Line 2767  String LSCPServer::SetEcho(yyparse_param Line 3833  String LSCPServer::SetEcho(yyparse_param
3833      }      }
3834      return result.Produce();      return result.Produce();
3835  }  }
3836    
3837    }

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

  ViewVC Help
Powered by ViewVC