/[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 1108 by iliev, Thu Mar 22 20:39:04 2007 UTC revision 1695 by schoenebeck, Sat Feb 16 01:09:33 2008 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2008 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 24  Line 24 
24  #include "lscpserver.h"  #include "lscpserver.h"
25  #include "lscpresultset.h"  #include "lscpresultset.h"
26  #include "lscpevent.h"  #include "lscpevent.h"
 #include "../common/global.h"  
27    
28    #if defined(WIN32)
29    #include <windows.h>
30    #else
31  #include <fcntl.h>  #include <fcntl.h>
32    #endif
33    
34  #if HAVE_SQLITE3  #if ! HAVE_SQLITE3
35  # include "sqlite3.h"  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
36  #endif  #endif
37    
38  #include "../engines/EngineFactory.h"  #include "../engines/EngineFactory.h"
# Line 37  Line 40 
40  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
41  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
42    
43    
44    /**
45     * Returns a copy of the given string where all special characters are
46     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
47     * to escape LSCP response fields in case the respective response field is
48     * actually defined as using escape sequences in the LSCP specs.
49     *
50     * @e Caution: DO NOT use this function for escaping path based responses,
51     * use the Path class (src/common/Path.h) for this instead!
52     */
53    static String _escapeLscpResponse(String txt) {
54        for (int i = 0; i < txt.length(); i++) {
55            const char c = txt.c_str()[i];
56            if (
57                !(c >= '0' && c <= '9') &&
58                !(c >= 'a' && c <= 'z') &&
59                !(c >= 'A' && c <= 'Z') &&
60                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
61                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
62                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
63                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
64                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
65                !(c == '@') && !(c == '[') && !(c == ']') &&
66                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
67                !(c == '|') && !(c == '}') && !(c == '~')
68            ) {
69                // convert the "special" character into a "\xHH" LSCP escape sequence
70                char buf[5];
71                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
72                txt.replace(i, 1, buf);
73                i += 3;
74            }
75        }
76        return txt;
77    }
78    
79  /**  /**
80   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
81   * The big assumption here is that LSCPServer is going to remain a singleton.   * The big assumption here is that LSCPServer is going to remain a singleton.
# Line 53  Line 92 
92  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
93  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
94  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
95    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
96  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
97  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
98  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
# Line 61  Mutex LSCPServer::NotifyBufferMutex = Mu Line 101  Mutex LSCPServer::NotifyBufferMutex = Mu
101  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
102  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
103    
104  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) {
105      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
106      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
107      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 81  LSCPServer::LSCPServer(Sampler* pSampler Line 121  LSCPServer::LSCPServer(Sampler* pSampler
121      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
122      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
123      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
124        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
125        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
126        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
128        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
129      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
131      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
132      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
133        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
134        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
135      hSocket = -1;      hSocket = -1;
136  }  }
137    
138  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
139    #if defined(WIN32)
140        if (hSocket >= 0) closesocket(hSocket);
141    #else
142      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
143    #endif
144    }
145    
146    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
147        this->pParent = pParent;
148    }
149    
150    LSCPServer::EventHandler::~EventHandler() {
151        std::vector<midi_listener_entry> l = channelMidiListeners;
152        channelMidiListeners.clear();
153        for (int i = 0; i < l.size(); i++)
154            delete l[i].pMidiListener;
155    }
156    
157    void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
158        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
159    }
160    
161    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
162        pChannel->AddEngineChangeListener(this);
163    }
164    
165    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
166        if (!pChannel->GetEngineChannel()) return;
167        EngineToBeChanged(pChannel->Index());
168    }
169    
170    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
171        SamplerChannel* pSamplerChannel =
172            pParent->pSampler->GetSamplerChannel(ChannelId);
173        if (!pSamplerChannel) return;
174        EngineChannel* pEngineChannel =
175            pSamplerChannel->GetEngineChannel();
176        if (!pEngineChannel) return;
177        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
178            if ((*iter).pEngineChannel == pEngineChannel) {
179                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
180                pEngineChannel->Disconnect(pMidiListener);
181                channelMidiListeners.erase(iter);
182                delete pMidiListener;
183                return;
184            }
185        }
186    }
187    
188    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
189        SamplerChannel* pSamplerChannel =
190            pParent->pSampler->GetSamplerChannel(ChannelId);
191        if (!pSamplerChannel) return;
192        EngineChannel* pEngineChannel =
193            pSamplerChannel->GetEngineChannel();
194        if (!pEngineChannel) return;
195        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
196        pEngineChannel->Connect(pMidiListener);
197        midi_listener_entry entry = {
198            pSamplerChannel, pEngineChannel, pMidiListener
199        };
200        channelMidiListeners.push_back(entry);
201    }
202    
203    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
204        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
205    }
206    
207    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
208        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
209    }
210    
211    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
212        pDevice->RemoveMidiPortCountListener(this);
213        for (int i = 0; i < pDevice->PortCount(); ++i)
214            MidiPortToBeRemoved(pDevice->GetPort(i));
215    }
216    
217    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
218        pDevice->AddMidiPortCountListener(this);
219        for (int i = 0; i < pDevice->PortCount(); ++i)
220            MidiPortAdded(pDevice->GetPort(i));
221    }
222    
223    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
224        // yet unused
225    }
226    
227    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
228        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
229            if ((*iter).pPort == pPort) {
230                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
231                pPort->Disconnect(pMidiListener);
232                deviceMidiListeners.erase(iter);
233                delete pMidiListener;
234                return;
235            }
236        }
237    }
238    
239    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
240        // find out the device ID
241        std::map<uint, MidiInputDevice*> devices =
242            pParent->pSampler->GetMidiInputDevices();
243        for (
244            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
245            iter != devices.end(); ++iter
246        ) {
247            if (iter->second == pPort->GetDevice()) { // found
248                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
249                pPort->Connect(pMidiListener);
250                device_midi_listener_entry entry = {
251                    pPort, pMidiListener, iter->first
252                };
253                deviceMidiListeners.push_back(entry);
254                return;
255            }
256        }
257    }
258    
259    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
260        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
261    }
262    
263    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
264        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
265    }
266    
267    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
268        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
269    }
270    
271    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
272        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
273    }
274    
275    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
276        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
277    }
278    
279    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
280        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
281    }
282    
283    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
284        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
285    }
286    
287    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
288        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
289    }
290    
291    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
292        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
293    }
294    
295    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
296        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
297    }
298    
299    #if HAVE_SQLITE3
300    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
301        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
302    }
303    
304    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
305        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
306    }
307    
308    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
309        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
310        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
311        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
312    }
313    
314    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
315        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
316    }
317    
318    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
319        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
320    }
321    
322    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
323        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
324        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
325        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
326    }
327    
328    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
329        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
330  }  }
331    #endif // HAVE_SQLITE3
332    
333    
334  /**  /**
335   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 106  int LSCPServer::WaitUntilInitialized(lon Line 346  int LSCPServer::WaitUntilInitialized(lon
346  }  }
347    
348  int LSCPServer::Main() {  int LSCPServer::Main() {
349            #if defined(WIN32)
350            WSADATA wsaData;
351            int iResult;
352            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
353            if (iResult != 0) {
354                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
355                    exit(EXIT_FAILURE);
356            }
357            #endif
358      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
359      if (hSocket < 0) {      if (hSocket < 0) {
360          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 119  int LSCPServer::Main() { Line 368  int LSCPServer::Main() {
368              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
369                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
370                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
371                        #if defined(WIN32)
372                        closesocket(hSocket);
373                        #else
374                      close(hSocket);                      close(hSocket);
375                        #endif
376                      //return -1;                      //return -1;
377                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
378                  }                  }
# Line 132  int LSCPServer::Main() { Line 385  int LSCPServer::Main() {
385      listen(hSocket, 1);      listen(hSocket, 1);
386      Initialized.Set(true);      Initialized.Set(true);
387    
388        // Registering event listeners
389        pSampler->AddChannelCountListener(&eventHandler);
390        pSampler->AddAudioDeviceCountListener(&eventHandler);
391        pSampler->AddMidiDeviceCountListener(&eventHandler);
392        pSampler->AddVoiceCountListener(&eventHandler);
393        pSampler->AddStreamCountListener(&eventHandler);
394        pSampler->AddBufferFillListener(&eventHandler);
395        pSampler->AddTotalStreamCountListener(&eventHandler);
396        pSampler->AddTotalVoiceCountListener(&eventHandler);
397        pSampler->AddFxSendCountListener(&eventHandler);
398        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
399        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
400        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
401        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
402    #if HAVE_SQLITE3
403        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
404    #endif
405      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
406      sockaddr_in client;      sockaddr_in client;
407      int length = sizeof(client);      int length = sizeof(client);
# Line 142  int LSCPServer::Main() { Line 412  int LSCPServer::Main() {
412      timeval timeout;      timeval timeout;
413    
414      while (true) {      while (true) {
415            #if CONFIG_PTHREAD_TESTCANCEL
416                    TestCancel();
417            #endif
418          // 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
419          {          {
420              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 163  int LSCPServer::Main() { Line 436  int LSCPServer::Main() {
436              }              }
437          }          }
438    
439            // check if MIDI data arrived on some engine channel
440            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
441                const EventHandler::midi_listener_entry entry =
442                    eventHandler.channelMidiListeners[i];
443                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
444                if (pMidiListener->NotesChanged()) {
445                    for (int iNote = 0; iNote < 128; iNote++) {
446                        if (pMidiListener->NoteChanged(iNote)) {
447                            const bool bActive = pMidiListener->NoteIsActive(iNote);
448                            LSCPServer::SendLSCPNotify(
449                                LSCPEvent(
450                                    LSCPEvent::event_channel_midi,
451                                    entry.pSamplerChannel->Index(),
452                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
453                                    iNote,
454                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
455                                            : pMidiListener->NoteOffVelocity(iNote)
456                                )
457                            );
458                        }
459                    }
460                }
461            }
462    
463            // check if MIDI data arrived on some MIDI device
464            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
465                const EventHandler::device_midi_listener_entry entry =
466                    eventHandler.deviceMidiListeners[i];
467                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
468                if (pMidiListener->NotesChanged()) {
469                    for (int iNote = 0; iNote < 128; iNote++) {
470                        if (pMidiListener->NoteChanged(iNote)) {
471                            const bool bActive = pMidiListener->NoteIsActive(iNote);
472                            LSCPServer::SendLSCPNotify(
473                                LSCPEvent(
474                                    LSCPEvent::event_device_midi,
475                                    entry.uiDeviceID,
476                                    entry.pPort->GetPortNumber(),
477                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
478                                    iNote,
479                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
480                                            : pMidiListener->NoteOffVelocity(iNote)
481                                )
482                            );
483                        }
484                    }
485                }
486            }
487    
488          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
489          NotifyBufferMutex.Lock();          NotifyBufferMutex.Lock();
490          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 185  int LSCPServer::Main() { Line 507  int LSCPServer::Main() {
507                  continue; //Nothing try again                  continue; //Nothing try again
508          if (retval == -1) {          if (retval == -1) {
509                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
510                    #if defined(WIN32)
511                    closesocket(hSocket);
512                    #else
513                  close(hSocket);                  close(hSocket);
514                    #endif
515                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
516          }          }
517    
# Line 197  int LSCPServer::Main() { Line 523  int LSCPServer::Main() {
523                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
524                  }                  }
525    
526                    #if defined(WIN32)
527                    u_long nonblock_io = 1;
528                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
529                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
530                      exit(EXIT_FAILURE);
531                    }
532            #else
533                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
534                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
535                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
536                  }                  }
537                    #endif
538    
539                  // Parser initialization                  // Parser initialization
540                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 224  int LSCPServer::Main() { Line 558  int LSCPServer::Main() {
558                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
559                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
560                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
561                                    itCurrentSession = iter; // another hack
562                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
563                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
564                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
565                                  }                                  }
566                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
567                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
568                                    itCurrentSession = Sessions.end(); // hack as well
569                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
570                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
571                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 257  void LSCPServer::CloseConnection( std::v Line 593  void LSCPServer::CloseConnection( std::v
593          NotifyMutex.Lock();          NotifyMutex.Lock();
594          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
595          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
596            #if defined(WIN32)
597            closesocket(socket);
598            #else
599          close(socket);          close(socket);
600            #endif
601          NotifyMutex.Unlock();          NotifyMutex.Unlock();
602  }  }
603    
604    void LSCPServer::LockRTNotify() {
605        RTNotifyMutex.Lock();
606    }
607    
608    void LSCPServer::UnlockRTNotify() {
609        RTNotifyMutex.Unlock();
610    }
611    
612  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
613          int subs = 0;          int subs = 0;
614          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 322  extern int GetLSCPCommand( void *buf, in Line 670  extern int GetLSCPCommand( void *buf, in
670          return command.size();          return command.size();
671  }  }
672    
673    extern yyparse_param_t* GetCurrentYaccSession() {
674        return &(*itCurrentSession);
675    }
676    
677  /**  /**
678   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
679   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
# Line 332  bool LSCPServer::GetLSCPCommand( std::ve Line 684  bool LSCPServer::GetLSCPCommand( std::ve
684          char c;          char c;
685          int i = 0;          int i = 0;
686          while (true) {          while (true) {
687                    #if defined(WIN32)
688                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
689                    #else
690                  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
691                    #endif
692                  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
693                          CloseConnection(iter);                          CloseConnection(iter);
694                          break;                          break;
# Line 347  bool LSCPServer::GetLSCPCommand( std::ve Line 703  bool LSCPServer::GetLSCPCommand( std::ve
703                          }                          }
704                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
705                  }                  }
706                    #if defined(WIN32)
707                    if (result == SOCKET_ERROR) {
708                        int wsa_lasterror = WSAGetLastError();
709                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
710                                    return false;
711                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
712                            CloseConnection(iter);
713                            break;
714                    }
715                    #else
716                  if (result == -1) {                  if (result == -1) {
717                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
718                                  return false;                                  return false;
# Line 385  bool LSCPServer::GetLSCPCommand( std::ve Line 751  bool LSCPServer::GetLSCPCommand( std::ve
751                          CloseConnection(iter);                          CloseConnection(iter);
752                          break;                          break;
753                  }                  }
754                    #endif
755          }          }
756          return false;          return false;
757  }  }
# Line 502  String LSCPServer::DestroyMidiInputDevic Line 869  String LSCPServer::DestroyMidiInputDevic
869      return result.Produce();      return result.Produce();
870  }  }
871    
872    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
873        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
874        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
875    
876        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
877        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
878    
879        return pEngineChannel;
880    }
881    
882  /**  /**
883   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
884   */   */
# Line 648  String LSCPServer::GetEngineInfo(String Line 1025  String LSCPServer::GetEngineInfo(String
1025      LockRTNotify();      LockRTNotify();
1026      try {      try {
1027          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1028          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1029          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1030          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1031      }      }
# Line 682  String LSCPServer::GetChannelInfo(uint u Line 1059  String LSCPServer::GetChannelInfo(uint u
1059          String AudioRouting;          String AudioRouting;
1060          int Mute = 0;          int Mute = 0;
1061          bool Solo = false;          bool Solo = false;
1062          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
1063    
1064          if (pEngineChannel) {          if (pEngineChannel) {
1065              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 721  String LSCPServer::GetChannelInfo(uint u Line 1098  String LSCPServer::GetChannelInfo(uint u
1098          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1099          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1100    
1101            // convert the filename into the correct encoding as defined for LSCP
1102            // (especially in terms of special characters -> escape sequences)
1103            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1104    #if WIN32
1105                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1106    #else
1107                // assuming POSIX
1108                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1109    #endif
1110            }
1111    
1112          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1113          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1114          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1115          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1116          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1117          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1665  String LSCPServer::GetMidiInstrumentMapp Line 2053  String LSCPServer::GetMidiInstrumentMapp
2053          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);
2054          if (iter == mappings.end()) result.Error("there is no map entry with that index");          if (iter == mappings.end()) result.Error("there is no map entry with that index");
2055          else { // found          else { // found
2056              result.Add("NAME", iter->second.Name);  
2057                // convert the filename into the correct encoding as defined for LSCP
2058                // (especially in terms of special characters -> escape sequences)
2059    #if WIN32
2060                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
2061    #else
2062                // assuming POSIX
2063                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
2064    #endif
2065    
2066                result.Add("NAME", _escapeLscpResponse(iter->second.Name));
2067              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
2068              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              result.Add("INSTRUMENT_FILE", instrumentFileName);
2069              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
2070              String instrumentName;              String instrumentName;
2071              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 1680  String LSCPServer::GetMidiInstrumentMapp Line 2078  String LSCPServer::GetMidiInstrumentMapp
2078                  }                  }
2079                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
2080              }              }
2081              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2082              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
2083                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
2084                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1835  String LSCPServer::GetMidiInstrumentMap( Line 2233  String LSCPServer::GetMidiInstrumentMap(
2233      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2234      LSCPResultSet result;      LSCPResultSet result;
2235      try {      try {
2236          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2237            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2238      } catch (Exception e) {      } catch (Exception e) {
2239          result.Error(e);          result.Error(e);
2240      }      }
# Line 1884  String LSCPServer::CreateFxSend(uint uiS Line 2283  String LSCPServer::CreateFxSend(uint uiS
2283      dmsg(2,("LSCPServer: CreateFxSend()\n"));      dmsg(2,("LSCPServer: CreateFxSend()\n"));
2284      LSCPResultSet result;      LSCPResultSet result;
2285      try {      try {
2286          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");  
2287    
2288          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2289          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
# Line 1904  String LSCPServer::DestroyFxSend(uint ui Line 2299  String LSCPServer::DestroyFxSend(uint ui
2299      dmsg(2,("LSCPServer: DestroyFxSend()\n"));      dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2300      LSCPResultSet result;      LSCPResultSet result;
2301      try {      try {
2302          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");  
2303    
2304          FxSend* pFxSend = NULL;          FxSend* pFxSend = NULL;
2305          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
# Line 1929  String LSCPServer::GetFxSends(uint uiSam Line 2320  String LSCPServer::GetFxSends(uint uiSam
2320      dmsg(2,("LSCPServer: GetFxSends()\n"));      dmsg(2,("LSCPServer: GetFxSends()\n"));
2321      LSCPResultSet result;      LSCPResultSet result;
2322      try {      try {
2323          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");  
2324    
2325          result.Add(pEngineChannel->GetFxSendCount());          result.Add(pEngineChannel->GetFxSendCount());
2326      } catch (Exception e) {      } catch (Exception e) {
# Line 1947  String LSCPServer::ListFxSends(uint uiSa Line 2334  String LSCPServer::ListFxSends(uint uiSa
2334      LSCPResultSet result;      LSCPResultSet result;
2335      String list;      String list;
2336      try {      try {
2337          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");  
2338    
2339          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2340              FxSend* pFxSend = pEngineChannel->GetFxSend(i);              FxSend* pFxSend = pEngineChannel->GetFxSend(i);
# Line 1965  String LSCPServer::ListFxSends(uint uiSa Line 2348  String LSCPServer::ListFxSends(uint uiSa
2348      return result.Produce();      return result.Produce();
2349  }  }
2350    
2351    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2352        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2353    
2354        FxSend* pFxSend = NULL;
2355        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2356            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2357                pFxSend = pEngineChannel->GetFxSend(i);
2358                break;
2359            }
2360        }
2361        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2362        return pFxSend;
2363    }
2364    
2365  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2366      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2367      LSCPResultSet result;      LSCPResultSet result;
2368      try {      try {
2369          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2370          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2371    
2372          // gather audio routing informations          // gather audio routing informations
2373          String AudioRouting;          String AudioRouting;
# Line 1992  String LSCPServer::GetFxSendInfo(uint ui Line 2377  String LSCPServer::GetFxSendInfo(uint ui
2377          }          }
2378    
2379          // success          // success
2380          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2381          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2382          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2383          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
# Line 2002  String LSCPServer::GetFxSendInfo(uint ui Line 2387  String LSCPServer::GetFxSendInfo(uint ui
2387      return result.Produce();      return result.Produce();
2388  }  }
2389    
2390  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {  String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2391      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));      dmsg(2,("LSCPServer: SetFxSendName()\n"));
2392      LSCPResultSet result;      LSCPResultSet result;
2393      try {      try {
2394          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2395    
2396          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetName(Name);
2397          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2398        } catch (Exception e) {
2399            result.Error(e);
2400        }
2401        return result.Produce();
2402    }
2403    
2404          FxSend* pFxSend = NULL;  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2405          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2406              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2407                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2408                  break;          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2409    
2410          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2411          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2033  String LSCPServer::SetFxSendMidiControll Line 2419  String LSCPServer::SetFxSendMidiControll
2419      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2420      LSCPResultSet result;      LSCPResultSet result;
2421      try {      try {
2422          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2423    
2424          pFxSend->SetMidiController(MidiController);          pFxSend->SetMidiController(MidiController);
2425          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2060  String LSCPServer::SetFxSendLevel(uint u Line 2433  String LSCPServer::SetFxSendLevel(uint u
2433      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2434      LSCPResultSet result;      LSCPResultSet result;
2435      try {      try {
2436          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2437    
2438          pFxSend->SetLevel((float)dLevel);          pFxSend->SetLevel((float)dLevel);
2439          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2083  String LSCPServer::SetFxSendLevel(uint u Line 2443  String LSCPServer::SetFxSendLevel(uint u
2443      return result.Produce();      return result.Produce();
2444  }  }
2445    
2446    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2447        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2448        LSCPResultSet result;
2449        try {
2450            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2451            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2452            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2453            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2454            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2455            Engine* pEngine = pEngineChannel->GetEngine();
2456            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2457            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2458            InstrumentManager::instrument_id_t instrumentID;
2459            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2460            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2461            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2462        } catch (Exception e) {
2463            result.Error(e);
2464        }
2465        return result.Produce();
2466    }
2467    
2468  /**  /**
2469   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2470   */   */
# Line 2118  String LSCPServer::ResetSampler() { Line 2500  String LSCPServer::ResetSampler() {
2500   */   */
2501  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2502      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2503        const std::string description =
2504            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2505      LSCPResultSet result;      LSCPResultSet result;
2506      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2507      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2508      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2509    #if HAVE_SQLITE3
2510        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2511    #else
2512        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2513    #endif
2514    
2515        return result.Produce();
2516    }
2517    
2518    /**
2519     * Will be called by the parser to return the current number of all active streams.
2520     */
2521    String LSCPServer::GetTotalStreamCount() {
2522        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2523        LSCPResultSet result;
2524        result.Add(pSampler->GetDiskStreamCount());
2525      return result.Produce();      return result.Produce();
2526  }  }
2527    
# Line 2163  String LSCPServer::SetGlobalVolume(doubl Line 2563  String LSCPServer::SetGlobalVolume(doubl
2563      return result.Produce();      return result.Produce();
2564  }  }
2565    
2566    String LSCPServer::GetFileInstruments(String Filename) {
2567        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2568        LSCPResultSet result;
2569        try {
2570            VerifyFile(Filename);
2571        } catch (Exception e) {
2572            result.Error(e);
2573            return result.Produce();
2574        }
2575        // try to find a sampler engine that can handle the file
2576        bool bFound = false;
2577        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2578        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2579            Engine* pEngine = NULL;
2580            try {
2581                pEngine = EngineFactory::Create(engineTypes[i]);
2582                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2583                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2584                if (pManager) {
2585                    std::vector<InstrumentManager::instrument_id_t> IDs =
2586                        pManager->GetInstrumentFileContent(Filename);
2587                    // return the amount of instruments in the file
2588                    result.Add(IDs.size());
2589                    // no more need to ask other engine types
2590                    bFound = true;
2591                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2592            } catch (Exception e) {
2593                // NOOP, as exception is thrown if engine doesn't support file
2594            }
2595            if (pEngine) EngineFactory::Destroy(pEngine);
2596        }
2597    
2598        if (!bFound) result.Error("Unknown file format");
2599        return result.Produce();
2600    }
2601    
2602    String LSCPServer::ListFileInstruments(String Filename) {
2603        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2604        LSCPResultSet result;
2605        try {
2606            VerifyFile(Filename);
2607        } catch (Exception e) {
2608            result.Error(e);
2609            return result.Produce();
2610        }
2611        // try to find a sampler engine that can handle the file
2612        bool bFound = false;
2613        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2614        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2615            Engine* pEngine = NULL;
2616            try {
2617                pEngine = EngineFactory::Create(engineTypes[i]);
2618                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2619                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2620                if (pManager) {
2621                    std::vector<InstrumentManager::instrument_id_t> IDs =
2622                        pManager->GetInstrumentFileContent(Filename);
2623                    // return a list of IDs of the instruments in the file
2624                    String s;
2625                    for (int j = 0; j < IDs.size(); j++) {
2626                        if (s.size()) s += ",";
2627                        s += ToString(IDs[j].Index);
2628                    }
2629                    result.Add(s);
2630                    // no more need to ask other engine types
2631                    bFound = true;
2632                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2633            } catch (Exception e) {
2634                // NOOP, as exception is thrown if engine doesn't support file
2635            }
2636            if (pEngine) EngineFactory::Destroy(pEngine);
2637        }
2638    
2639        if (!bFound) result.Error("Unknown file format");
2640        return result.Produce();
2641    }
2642    
2643    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2644        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2645        LSCPResultSet result;
2646        try {
2647            VerifyFile(Filename);
2648        } catch (Exception e) {
2649            result.Error(e);
2650            return result.Produce();
2651        }
2652        InstrumentManager::instrument_id_t id;
2653        id.FileName = Filename;
2654        id.Index    = InstrumentID;
2655        // try to find a sampler engine that can handle the file
2656        bool bFound = false;
2657        bool bFatalErr = false;
2658        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2659        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2660            Engine* pEngine = NULL;
2661            try {
2662                pEngine = EngineFactory::Create(engineTypes[i]);
2663                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2664                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2665                if (pManager) {
2666                    // check if the instrument index is valid
2667                    // FIXME: this won't work if an engine only supports parts of the instrument file
2668                    std::vector<InstrumentManager::instrument_id_t> IDs =
2669                        pManager->GetInstrumentFileContent(Filename);
2670                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2671                        std::stringstream ss;
2672                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2673                        bFatalErr = true;
2674                        throw Exception(ss.str());
2675                    }
2676                    // get the info of the requested instrument
2677                    InstrumentManager::instrument_info_t info =
2678                        pManager->GetInstrumentInfo(id);
2679                    // return detailed informations about the file
2680                    result.Add("NAME", info.InstrumentName);
2681                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2682                    result.Add("FORMAT_VERSION", info.FormatVersion);
2683                    result.Add("PRODUCT", info.Product);
2684                    result.Add("ARTISTS", info.Artists);
2685                    // no more need to ask other engine types
2686                    bFound = true;
2687                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2688            } catch (Exception e) {
2689                // usually NOOP, as exception is thrown if engine doesn't support file
2690                if (bFatalErr) result.Error(e);
2691            }
2692            if (pEngine) EngineFactory::Destroy(pEngine);
2693        }
2694    
2695        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2696        return result.Produce();
2697    }
2698    
2699    void LSCPServer::VerifyFile(String Filename) {
2700        #if WIN32
2701        WIN32_FIND_DATA win32FileAttributeData;
2702        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2703        if (!res) {
2704            std::stringstream ss;
2705            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2706            throw Exception(ss.str());
2707        }
2708        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2709            throw Exception("Directory is specified");
2710        }
2711        #else
2712        struct stat statBuf;
2713        int res = stat(Filename.c_str(), &statBuf);
2714        if (res) {
2715            std::stringstream ss;
2716            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2717            throw Exception(ss.str());
2718        }
2719    
2720        if (S_ISDIR(statBuf.st_mode)) {
2721            throw Exception("Directory is specified");
2722        }
2723        #endif
2724    }
2725    
2726  /**  /**
2727   * 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
2728   * server for receiving event messages.   * server for receiving event messages.
# Line 2189  String LSCPServer::UnsubscribeNotificati Line 2749  String LSCPServer::UnsubscribeNotificati
2749      return result.Produce();      return result.Produce();
2750  }  }
2751    
2752  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2753                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2754  {      LSCPResultSet result;
2755      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2756      resultSet->Add(argc, argv);      try {
2757      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2758        } catch (Exception e) {
2759             result.Error(e);
2760        }
2761    #else
2762        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2763    #endif
2764        return result.Produce();
2765    }
2766    
2767    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2768        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2769        LSCPResultSet result;
2770    #if HAVE_SQLITE3
2771        try {
2772            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2773        } catch (Exception e) {
2774             result.Error(e);
2775        }
2776    #else
2777        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2778    #endif
2779        return result.Produce();
2780    }
2781    
2782    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2783        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2784        LSCPResultSet result;
2785    #if HAVE_SQLITE3
2786        try {
2787            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2788        } catch (Exception e) {
2789             result.Error(e);
2790        }
2791    #else
2792        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2793    #endif
2794        return result.Produce();
2795    }
2796    
2797    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2798        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2799        LSCPResultSet result;
2800    #if HAVE_SQLITE3
2801        try {
2802            String list;
2803            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2804    
2805            for (int i = 0; i < dirs->size(); i++) {
2806                if (list != "") list += ",";
2807                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2808            }
2809    
2810            result.Add(list);
2811        } catch (Exception e) {
2812             result.Error(e);
2813        }
2814    #else
2815        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2816    #endif
2817        return result.Produce();
2818    }
2819    
2820    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2821        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2822        LSCPResultSet result;
2823    #if HAVE_SQLITE3
2824        try {
2825            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2826    
2827            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2828            result.Add("CREATED", info.Created);
2829            result.Add("MODIFIED", info.Modified);
2830        } catch (Exception e) {
2831             result.Error(e);
2832        }
2833    #else
2834        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2835    #endif
2836        return result.Produce();
2837    }
2838    
2839    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2840        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2841        LSCPResultSet result;
2842    #if HAVE_SQLITE3
2843        try {
2844            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2845        } catch (Exception e) {
2846             result.Error(e);
2847        }
2848    #else
2849        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2850    #endif
2851        return result.Produce();
2852    }
2853    
2854    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2855        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2856        LSCPResultSet result;
2857    #if HAVE_SQLITE3
2858        try {
2859            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2860        } catch (Exception e) {
2861             result.Error(e);
2862        }
2863    #else
2864        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2865    #endif
2866        return result.Produce();
2867    }
2868    
2869    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2870        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2871        LSCPResultSet result;
2872    #if HAVE_SQLITE3
2873        try {
2874            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2875        } catch (Exception e) {
2876             result.Error(e);
2877        }
2878    #else
2879        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2880    #endif
2881        return result.Produce();
2882    }
2883    
2884    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2885        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2886        LSCPResultSet result;
2887    #if HAVE_SQLITE3
2888        try {
2889            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2890        } catch (Exception e) {
2891             result.Error(e);
2892        }
2893    #else
2894        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2895    #endif
2896        return result.Produce();
2897    }
2898    
2899    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2900        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2901        LSCPResultSet result;
2902    #if HAVE_SQLITE3
2903        try {
2904            int id;
2905            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2906            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2907            if (bBackground) result = id;
2908        } catch (Exception e) {
2909             result.Error(e);
2910        }
2911    #else
2912        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2913    #endif
2914        return result.Produce();
2915    }
2916    
2917    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2918        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2919        LSCPResultSet result;
2920    #if HAVE_SQLITE3
2921        try {
2922            int id;
2923            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2924            if (ScanMode.compare("RECURSIVE") == 0) {
2925               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2926            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2927               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2928            } else if (ScanMode.compare("FLAT") == 0) {
2929               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2930            } else {
2931                throw Exception("Unknown scan mode: " + ScanMode);
2932            }
2933    
2934            if (bBackground) result = id;
2935        } catch (Exception e) {
2936             result.Error(e);
2937        }
2938    #else
2939        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2940    #endif
2941        return result.Produce();
2942    }
2943    
2944    String LSCPServer::RemoveDbInstrument(String Instr) {
2945        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2946        LSCPResultSet result;
2947    #if HAVE_SQLITE3
2948        try {
2949            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2950        } catch (Exception e) {
2951             result.Error(e);
2952        }
2953    #else
2954        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2955    #endif
2956        return result.Produce();
2957    }
2958    
2959    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2960        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2961        LSCPResultSet result;
2962    #if HAVE_SQLITE3
2963        try {
2964            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2965        } catch (Exception e) {
2966             result.Error(e);
2967        }
2968    #else
2969        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2970    #endif
2971        return result.Produce();
2972  }  }
2973    
2974  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2975        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2976      LSCPResultSet result;      LSCPResultSet result;
2977  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2978      char* zErrMsg = NULL;      try {
2979      sqlite3 *db;          String list;
2980      String selectStr = "SELECT " + query;          StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2981    
2982      int rc = sqlite3_open("linuxsampler.db", &db);          for (int i = 0; i < instrs->size(); i++) {
2983      if (rc == SQLITE_OK)              if (list != "") list += ",";
2984      {              list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2985              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);          }
2986    
2987            result.Add(list);
2988        } catch (Exception e) {
2989             result.Error(e);
2990      }      }
2991      if ( rc != SQLITE_OK )  #else
2992      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2993              result.Error(String(zErrMsg), rc);  #endif
2994        return result.Produce();
2995    }
2996    
2997    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2998        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2999        LSCPResultSet result;
3000    #if HAVE_SQLITE3
3001        try {
3002            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
3003    
3004            result.Add("INSTRUMENT_FILE", info.InstrFile);
3005            result.Add("INSTRUMENT_NR", info.InstrNr);
3006            result.Add("FORMAT_FAMILY", info.FormatFamily);
3007            result.Add("FORMAT_VERSION", info.FormatVersion);
3008            result.Add("SIZE", (int)info.Size);
3009            result.Add("CREATED", info.Created);
3010            result.Add("MODIFIED", info.Modified);
3011            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3012            result.Add("IS_DRUM", info.IsDrum);
3013            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3014            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3015            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3016        } catch (Exception e) {
3017             result.Error(e);
3018      }      }
     sqlite3_close(db);  
3019  #else  #else
3020      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3021  #endif  #endif
3022      return result.Produce();      return result.Produce();
3023  }  }
3024    
3025    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3026        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3027        LSCPResultSet result;
3028    #if HAVE_SQLITE3
3029        try {
3030            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3031    
3032            result.Add("FILES_TOTAL", job.FilesTotal);
3033            result.Add("FILES_SCANNED", job.FilesScanned);
3034            result.Add("SCANNING", job.Scanning);
3035            result.Add("STATUS", job.Status);
3036        } catch (Exception e) {
3037             result.Error(e);
3038        }
3039    #else
3040        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3041    #endif
3042        return result.Produce();
3043    }
3044    
3045    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3046        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3047        LSCPResultSet result;
3048    #if HAVE_SQLITE3
3049        try {
3050            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3051        } catch (Exception e) {
3052             result.Error(e);
3053        }
3054    #else
3055        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3056    #endif
3057        return result.Produce();
3058    }
3059    
3060    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3061        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3062        LSCPResultSet result;
3063    #if HAVE_SQLITE3
3064        try {
3065            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3066        } catch (Exception e) {
3067             result.Error(e);
3068        }
3069    #else
3070        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3071    #endif
3072        return result.Produce();
3073    }
3074    
3075    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3076        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3077        LSCPResultSet result;
3078    #if HAVE_SQLITE3
3079        try {
3080            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3081        } catch (Exception e) {
3082             result.Error(e);
3083        }
3084    #else
3085        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3086    #endif
3087        return result.Produce();
3088    }
3089    
3090    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3091        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3092        LSCPResultSet result;
3093    #if HAVE_SQLITE3
3094        try {
3095            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3096        } catch (Exception e) {
3097             result.Error(e);
3098        }
3099    #else
3100        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3101    #endif
3102        return result.Produce();
3103    }
3104    
3105    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3106        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3107        LSCPResultSet result;
3108    #if HAVE_SQLITE3
3109        try {
3110            SearchQuery Query;
3111            std::map<String,String>::iterator iter;
3112            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3113                if (iter->first.compare("NAME") == 0) {
3114                    Query.Name = iter->second;
3115                } else if (iter->first.compare("CREATED") == 0) {
3116                    Query.SetCreated(iter->second);
3117                } else if (iter->first.compare("MODIFIED") == 0) {
3118                    Query.SetModified(iter->second);
3119                } else if (iter->first.compare("DESCRIPTION") == 0) {
3120                    Query.Description = iter->second;
3121                } else {
3122                    throw Exception("Unknown search criteria: " + iter->first);
3123                }
3124            }
3125    
3126            String list;
3127            StringListPtr pDirectories =
3128                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3129    
3130            for (int i = 0; i < pDirectories->size(); i++) {
3131                if (list != "") list += ",";
3132                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3133            }
3134    
3135            result.Add(list);
3136        } catch (Exception e) {
3137             result.Error(e);
3138        }
3139    #else
3140        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3141    #endif
3142        return result.Produce();
3143    }
3144    
3145    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3146        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3147        LSCPResultSet result;
3148    #if HAVE_SQLITE3
3149        try {
3150            SearchQuery Query;
3151            std::map<String,String>::iterator iter;
3152            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3153                if (iter->first.compare("NAME") == 0) {
3154                    Query.Name = iter->second;
3155                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3156                    Query.SetFormatFamilies(iter->second);
3157                } else if (iter->first.compare("SIZE") == 0) {
3158                    Query.SetSize(iter->second);
3159                } else if (iter->first.compare("CREATED") == 0) {
3160                    Query.SetCreated(iter->second);
3161                } else if (iter->first.compare("MODIFIED") == 0) {
3162                    Query.SetModified(iter->second);
3163                } else if (iter->first.compare("DESCRIPTION") == 0) {
3164                    Query.Description = iter->second;
3165                } else if (iter->first.compare("IS_DRUM") == 0) {
3166                    if (!strcasecmp(iter->second.c_str(), "true")) {
3167                        Query.InstrType = SearchQuery::DRUM;
3168                    } else {
3169                        Query.InstrType = SearchQuery::CHROMATIC;
3170                    }
3171                } else if (iter->first.compare("PRODUCT") == 0) {
3172                     Query.Product = iter->second;
3173                } else if (iter->first.compare("ARTISTS") == 0) {
3174                     Query.Artists = iter->second;
3175                } else if (iter->first.compare("KEYWORDS") == 0) {
3176                     Query.Keywords = iter->second;
3177                } else {
3178                    throw Exception("Unknown search criteria: " + iter->first);
3179                }
3180            }
3181    
3182            String list;
3183            StringListPtr pInstruments =
3184                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3185    
3186            for (int i = 0; i < pInstruments->size(); i++) {
3187                if (list != "") list += ",";
3188                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3189            }
3190    
3191            result.Add(list);
3192        } catch (Exception e) {
3193             result.Error(e);
3194        }
3195    #else
3196        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3197    #endif
3198        return result.Produce();
3199    }
3200    
3201    String LSCPServer::FormatInstrumentsDb() {
3202        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3203        LSCPResultSet result;
3204    #if HAVE_SQLITE3
3205        try {
3206            InstrumentsDb::GetInstrumentsDb()->Format();
3207        } catch (Exception e) {
3208             result.Error(e);
3209        }
3210    #else
3211        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3212    #endif
3213        return result.Produce();
3214    }
3215    
3216    
3217  /**  /**
3218   * 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
3219   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be

Legend:
Removed from v.1108  
changed lines
  Added in v.1695

  ViewVC Help
Powered by ViewVC