/[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 981 by iliev, Sun Dec 17 22:35:01 2006 UTC revision 1765 by persson, Sat Sep 6 16:44:42 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, 2006 Christian Schoenebeck                        *   *   Copyright (C) 2005 - 2008 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    
26  #include "lscpserver.h"  #include "lscpserver.h"
27  #include "lscpresultset.h"  #include "lscpresultset.h"
28  #include "lscpevent.h"  #include "lscpevent.h"
 //#include "../common/global.h"  
29    
30    #if defined(WIN32)
31    #include <windows.h>
32    #else
33  #include <fcntl.h>  #include <fcntl.h>
34    #endif
35    
36  #if HAVE_SQLITE3  #if ! HAVE_SQLITE3
37  # include "sqlite3.h"  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
38  #endif  #endif
39    
40  #include "../engines/EngineFactory.h"  #include "../engines/EngineFactory.h"
# Line 37  Line 42 
42  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
43  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
44    
45    namespace LinuxSampler {
46    
47    /**
48     * Returns a copy of the given string where all special characters are
49     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
50     * to escape LSCP response fields in case the respective response field is
51     * actually defined as using escape sequences in the LSCP specs.
52     *
53     * @e Caution: DO NOT use this function for escaping path based responses,
54     * use the Path class (src/common/Path.h) for this instead!
55     */
56    static String _escapeLscpResponse(String txt) {
57        for (int i = 0; i < txt.length(); i++) {
58            const char c = txt.c_str()[i];
59            if (
60                !(c >= '0' && c <= '9') &&
61                !(c >= 'a' && c <= 'z') &&
62                !(c >= 'A' && c <= 'Z') &&
63                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
64                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
65                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
66                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
67                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
68                !(c == '@') && !(c == '[') && !(c == ']') &&
69                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
70                !(c == '|') && !(c == '}') && !(c == '~')
71            ) {
72                // convert the "special" character into a "\xHH" LSCP escape sequence
73                char buf[5];
74                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
75                txt.replace(i, 1, buf);
76                i += 3;
77            }
78        }
79        return txt;
80    }
81    
82  /**  /**
83   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
84   * 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 95 
95  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
96  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
97  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
98    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
99  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
100  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
101  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 104  Mutex LSCPServer::NotifyBufferMutex = Mu
104  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
105  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
106    
107  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) {
108      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
109      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
110      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 75  LSCPServer::LSCPServer(Sampler* pSampler Line 118  LSCPServer::LSCPServer(Sampler* pSampler
118      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
119      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
120      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
121        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_count, "FX_SEND_COUNT");
122        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_info, "FX_SEND_INFO");
123      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");
124      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
125      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
126      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
128        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
129        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
131        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
132      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
133        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
134      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
135        LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
136        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
137        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
138      hSocket = -1;      hSocket = -1;
139  }  }
140    
141  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
142    #if defined(WIN32)
143        if (hSocket >= 0) closesocket(hSocket);
144    #else
145      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
146    #endif
147    }
148    
149    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
150        this->pParent = pParent;
151    }
152    
153    LSCPServer::EventHandler::~EventHandler() {
154        std::vector<midi_listener_entry> l = channelMidiListeners;
155        channelMidiListeners.clear();
156        for (int i = 0; i < l.size(); i++)
157            delete l[i].pMidiListener;
158    }
159    
160    void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
161        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
162    }
163    
164    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
165        pChannel->AddEngineChangeListener(this);
166    }
167    
168    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
169        if (!pChannel->GetEngineChannel()) return;
170        EngineToBeChanged(pChannel->Index());
171    }
172    
173    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
174        SamplerChannel* pSamplerChannel =
175            pParent->pSampler->GetSamplerChannel(ChannelId);
176        if (!pSamplerChannel) return;
177        EngineChannel* pEngineChannel =
178            pSamplerChannel->GetEngineChannel();
179        if (!pEngineChannel) return;
180        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
181            if ((*iter).pEngineChannel == pEngineChannel) {
182                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
183                pEngineChannel->Disconnect(pMidiListener);
184                channelMidiListeners.erase(iter);
185                delete pMidiListener;
186                return;
187            }
188        }
189    }
190    
191    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
192        SamplerChannel* pSamplerChannel =
193            pParent->pSampler->GetSamplerChannel(ChannelId);
194        if (!pSamplerChannel) return;
195        EngineChannel* pEngineChannel =
196            pSamplerChannel->GetEngineChannel();
197        if (!pEngineChannel) return;
198        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
199        pEngineChannel->Connect(pMidiListener);
200        midi_listener_entry entry = {
201            pSamplerChannel, pEngineChannel, pMidiListener
202        };
203        channelMidiListeners.push_back(entry);
204    }
205    
206    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
207        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
208    }
209    
210    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
211        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
212    }
213    
214    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
215        pDevice->RemoveMidiPortCountListener(this);
216        for (int i = 0; i < pDevice->PortCount(); ++i)
217            MidiPortToBeRemoved(pDevice->GetPort(i));
218    }
219    
220    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
221        pDevice->AddMidiPortCountListener(this);
222        for (int i = 0; i < pDevice->PortCount(); ++i)
223            MidiPortAdded(pDevice->GetPort(i));
224    }
225    
226    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
227        // yet unused
228    }
229    
230    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
231        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
232            if ((*iter).pPort == pPort) {
233                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
234                pPort->Disconnect(pMidiListener);
235                deviceMidiListeners.erase(iter);
236                delete pMidiListener;
237                return;
238            }
239        }
240    }
241    
242    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
243        // find out the device ID
244        std::map<uint, MidiInputDevice*> devices =
245            pParent->pSampler->GetMidiInputDevices();
246        for (
247            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
248            iter != devices.end(); ++iter
249        ) {
250            if (iter->second == pPort->GetDevice()) { // found
251                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
252                pPort->Connect(pMidiListener);
253                device_midi_listener_entry entry = {
254                    pPort, pMidiListener, iter->first
255                };
256                deviceMidiListeners.push_back(entry);
257                return;
258            }
259        }
260    }
261    
262    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
263        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
264    }
265    
266    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
267        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
268    }
269    
270    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
271        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
272    }
273    
274    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
275        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
276    }
277    
278    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
279        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
280    }
281    
282    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
283        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
284    }
285    
286    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
287        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
288    }
289    
290    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
291        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
292    }
293    
294    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
295        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
296    }
297    
298    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
299        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
300    }
301    
302    #if HAVE_SQLITE3
303    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
304        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
305    }
306    
307    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
308        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
309    }
310    
311    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
312        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
313        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
314        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
315  }  }
316    
317    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
318        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
319    }
320    
321    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
322        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
323    }
324    
325    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
326        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
327        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
328        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
329    }
330    
331    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
332        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
333    }
334    #endif // HAVE_SQLITE3
335    
336    
337  /**  /**
338   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
339   * accepting socket connections, if the server is already initialized then   * accepting socket connections, if the server is already initialized then
# Line 103  int LSCPServer::WaitUntilInitialized(lon Line 349  int LSCPServer::WaitUntilInitialized(lon
349  }  }
350    
351  int LSCPServer::Main() {  int LSCPServer::Main() {
352            #if defined(WIN32)
353            WSADATA wsaData;
354            int iResult;
355            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
356            if (iResult != 0) {
357                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
358                    exit(EXIT_FAILURE);
359            }
360            #endif
361      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
362      if (hSocket < 0) {      if (hSocket < 0) {
363          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 116  int LSCPServer::Main() { Line 371  int LSCPServer::Main() {
371              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
372                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
373                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
374                        #if defined(WIN32)
375                        closesocket(hSocket);
376                        #else
377                      close(hSocket);                      close(hSocket);
378                        #endif
379                      //return -1;                      //return -1;
380                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
381                  }                  }
# Line 129  int LSCPServer::Main() { Line 388  int LSCPServer::Main() {
388      listen(hSocket, 1);      listen(hSocket, 1);
389      Initialized.Set(true);      Initialized.Set(true);
390    
391        // Registering event listeners
392        pSampler->AddChannelCountListener(&eventHandler);
393        pSampler->AddAudioDeviceCountListener(&eventHandler);
394        pSampler->AddMidiDeviceCountListener(&eventHandler);
395        pSampler->AddVoiceCountListener(&eventHandler);
396        pSampler->AddStreamCountListener(&eventHandler);
397        pSampler->AddBufferFillListener(&eventHandler);
398        pSampler->AddTotalStreamCountListener(&eventHandler);
399        pSampler->AddTotalVoiceCountListener(&eventHandler);
400        pSampler->AddFxSendCountListener(&eventHandler);
401        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
402        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
403        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
404        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
405    #if HAVE_SQLITE3
406        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
407    #endif
408      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
409      sockaddr_in client;      sockaddr_in client;
410      int length = sizeof(client);      int length = sizeof(client);
# Line 139  int LSCPServer::Main() { Line 415  int LSCPServer::Main() {
415      timeval timeout;      timeval timeout;
416    
417      while (true) {      while (true) {
418            #if CONFIG_PTHREAD_TESTCANCEL
419                    TestCancel();
420            #endif
421          // 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
422          {          {
423              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 146  int LSCPServer::Main() { Line 425  int LSCPServer::Main() {
425              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
426              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
427                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
428                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
429                    }
430    
431                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
432                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
433                        if(fxs != NULL && fxs->IsInfoChanged()) {
434                            int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
435                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
436                            fxs->SetInfoChanged(false);
437                        }
438                    }
439                }
440            }
441    
442            // check if MIDI data arrived on some engine channel
443            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
444                const EventHandler::midi_listener_entry entry =
445                    eventHandler.channelMidiListeners[i];
446                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
447                if (pMidiListener->NotesChanged()) {
448                    for (int iNote = 0; iNote < 128; iNote++) {
449                        if (pMidiListener->NoteChanged(iNote)) {
450                            const bool bActive = pMidiListener->NoteIsActive(iNote);
451                            LSCPServer::SendLSCPNotify(
452                                LSCPEvent(
453                                    LSCPEvent::event_channel_midi,
454                                    entry.pSamplerChannel->Index(),
455                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
456                                    iNote,
457                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
458                                            : pMidiListener->NoteOffVelocity(iNote)
459                                )
460                            );
461                        }
462                    }
463                }
464            }
465    
466            // check if MIDI data arrived on some MIDI device
467            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
468                const EventHandler::device_midi_listener_entry entry =
469                    eventHandler.deviceMidiListeners[i];
470                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
471                if (pMidiListener->NotesChanged()) {
472                    for (int iNote = 0; iNote < 128; iNote++) {
473                        if (pMidiListener->NoteChanged(iNote)) {
474                            const bool bActive = pMidiListener->NoteIsActive(iNote);
475                            LSCPServer::SendLSCPNotify(
476                                LSCPEvent(
477                                    LSCPEvent::event_device_midi,
478                                    entry.uiDeviceID,
479                                    entry.pPort->GetPortNumber(),
480                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
481                                    iNote,
482                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
483                                            : pMidiListener->NoteOffVelocity(iNote)
484                                )
485                            );
486                        }
487                  }                  }
488              }              }
489          }          }
# Line 173  int LSCPServer::Main() { Line 510  int LSCPServer::Main() {
510                  continue; //Nothing try again                  continue; //Nothing try again
511          if (retval == -1) {          if (retval == -1) {
512                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
513                    #if defined(WIN32)
514                    closesocket(hSocket);
515                    #else
516                  close(hSocket);                  close(hSocket);
517                    #endif
518                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
519          }          }
520    
# Line 185  int LSCPServer::Main() { Line 526  int LSCPServer::Main() {
526                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
527                  }                  }
528    
529                    #if defined(WIN32)
530                    u_long nonblock_io = 1;
531                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
532                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
533                      exit(EXIT_FAILURE);
534                    }
535            #else
536                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
537                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
538                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
539                  }                  }
540                    #endif
541    
542                  // Parser initialization                  // Parser initialization
543                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 212  int LSCPServer::Main() { Line 561  int LSCPServer::Main() {
561                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
562                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
563                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
564                                    itCurrentSession = iter; // another hack
565                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
566                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
567                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
568                                  }                                  }
569                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
570                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
571                                    itCurrentSession = Sessions.end(); // hack as well
572                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
573                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
574                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 245  void LSCPServer::CloseConnection( std::v Line 596  void LSCPServer::CloseConnection( std::v
596          NotifyMutex.Lock();          NotifyMutex.Lock();
597          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
598          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
599            #if defined(WIN32)
600            closesocket(socket);
601            #else
602          close(socket);          close(socket);
603            #endif
604          NotifyMutex.Unlock();          NotifyMutex.Unlock();
605  }  }
606    
607    void LSCPServer::LockRTNotify() {
608        RTNotifyMutex.Lock();
609    }
610    
611    void LSCPServer::UnlockRTNotify() {
612        RTNotifyMutex.Unlock();
613    }
614    
615  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
616          int subs = 0;          int subs = 0;
617          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 310  extern int GetLSCPCommand( void *buf, in Line 673  extern int GetLSCPCommand( void *buf, in
673          return command.size();          return command.size();
674  }  }
675    
676    extern yyparse_param_t* GetCurrentYaccSession() {
677        return &(*itCurrentSession);
678    }
679    
680  /**  /**
681   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
682   * 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 320  bool LSCPServer::GetLSCPCommand( std::ve Line 687  bool LSCPServer::GetLSCPCommand( std::ve
687          char c;          char c;
688          int i = 0;          int i = 0;
689          while (true) {          while (true) {
690                    #if defined(WIN32)
691                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
692                    #else
693                  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
694                    #endif
695                  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
696                          CloseConnection(iter);                          CloseConnection(iter);
697                          break;                          break;
# Line 335  bool LSCPServer::GetLSCPCommand( std::ve Line 706  bool LSCPServer::GetLSCPCommand( std::ve
706                          }                          }
707                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
708                  }                  }
709                    #if defined(WIN32)
710                    if (result == SOCKET_ERROR) {
711                        int wsa_lasterror = WSAGetLastError();
712                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
713                                    return false;
714                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
715                            CloseConnection(iter);
716                            break;
717                    }
718                    #else
719                  if (result == -1) {                  if (result == -1) {
720                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
721                                  return false;                                  return false;
# Line 373  bool LSCPServer::GetLSCPCommand( std::ve Line 754  bool LSCPServer::GetLSCPCommand( std::ve
754                          CloseConnection(iter);                          CloseConnection(iter);
755                          break;                          break;
756                  }                  }
757                    #endif
758          }          }
759          return false;          return false;
760  }  }
# Line 490  String LSCPServer::DestroyMidiInputDevic Line 872  String LSCPServer::DestroyMidiInputDevic
872      return result.Produce();      return result.Produce();
873  }  }
874    
875    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
876        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
877        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
878    
879        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
880        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
881    
882        return pEngineChannel;
883    }
884    
885  /**  /**
886   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
887   */   */
# Line 636  String LSCPServer::GetEngineInfo(String Line 1028  String LSCPServer::GetEngineInfo(String
1028      LockRTNotify();      LockRTNotify();
1029      try {      try {
1030          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1031          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1032          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1033          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1034      }      }
# Line 670  String LSCPServer::GetChannelInfo(uint u Line 1062  String LSCPServer::GetChannelInfo(uint u
1062          String AudioRouting;          String AudioRouting;
1063          int Mute = 0;          int Mute = 0;
1064          bool Solo = false;          bool Solo = false;
1065          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
1066    
1067          if (pEngineChannel) {          if (pEngineChannel) {
1068              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 709  String LSCPServer::GetChannelInfo(uint u Line 1101  String LSCPServer::GetChannelInfo(uint u
1101          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1102          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1103    
1104            // convert the filename into the correct encoding as defined for LSCP
1105            // (especially in terms of special characters -> escape sequences)
1106            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1107    #if WIN32
1108                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1109    #else
1110                // assuming POSIX
1111                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1112    #endif
1113            }
1114    
1115          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1116          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1117          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1118          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1119          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1120          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1502  String LSCPServer::SetChannelSolo(bool b Line 1905  String LSCPServer::SetChannelSolo(bool b
1905    
1906          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1907          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
1908            
1909          pEngineChannel->SetSolo(bSolo);          pEngineChannel->SetSolo(bSolo);
1910            
1911          if(!oldSolo && bSolo) {          if(!oldSolo && bSolo) {
1912              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1913              if(!hadSoloChannel) MuteNonSoloChannels();              if(!hadSoloChannel) MuteNonSoloChannels();
1914          }          }
1915            
1916          if(oldSolo && !bSolo) {          if(oldSolo && !bSolo) {
1917              if(!HasSoloChannel()) UnmuteChannels();              if(!HasSoloChannel()) UnmuteChannels();
1918              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
# Line 1567  void  LSCPServer::UnmuteChannels() { Line 1970  void  LSCPServer::UnmuteChannels() {
1970      }      }
1971  }  }
1972    
1973  String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg, String EngineType, String InstrumentFile, uint InstrumentIndex, float Volume, MidiInstrumentMapper::mode_t LoadMode, String Name) {  String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg, String EngineType, String InstrumentFile, uint InstrumentIndex, float Volume, MidiInstrumentMapper::mode_t LoadMode, String Name, bool bModal) {
1974      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1975    
1976      midi_prog_index_t idx;      midi_prog_index_t idx;
# Line 1585  String LSCPServer::AddOrReplaceMIDIInstr Line 1988  String LSCPServer::AddOrReplaceMIDIInstr
1988    
1989      LSCPResultSet result;      LSCPResultSet result;
1990      try {      try {
1991          // PERSISTENT mapping commands might bloock for a long time, so in          // PERSISTENT mapping commands might block for a long time, so in
1992          // that case we add/replace the mapping in another thread          // that case we add/replace the mapping in another thread in case
1993          bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT);          // the NON_MODAL argument was supplied, non persistent mappings
1994            // should return immediately, so we don't need to do that for them
1995            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
1996          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
1997      } catch (Exception e) {      } catch (Exception e) {
1998          result.Error(e);          result.Error(e);
# Line 1616  String LSCPServer::GetMidiInstrumentMapp Line 2021  String LSCPServer::GetMidiInstrumentMapp
2021      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2022      LSCPResultSet result;      LSCPResultSet result;
2023      try {      try {
2024          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2025      } catch (Exception e) {      } catch (Exception e) {
2026          result.Error(e);          result.Error(e);
2027      }      }
# Line 1627  String LSCPServer::GetMidiInstrumentMapp Line 2032  String LSCPServer::GetMidiInstrumentMapp
2032  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2033      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2034      LSCPResultSet result;      LSCPResultSet result;
2035      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2036      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2037      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2038          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2039      }      }
     result.Add(totalMappings);  
2040      return result.Produce();      return result.Produce();
2041  }  }
2042    
# Line 1642  String LSCPServer::GetMidiInstrumentMapp Line 2044  String LSCPServer::GetMidiInstrumentMapp
2044      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2045      LSCPResultSet result;      LSCPResultSet result;
2046      try {      try {
2047          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2048          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2049          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
2050          idx.midi_prog     = MidiProg;  #if WIN32
2051            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2052    #else
2053            // assuming POSIX
2054            const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2055    #endif
2056    
2057          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2058          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          result.Add("ENGINE_NAME", entry.EngineName);
2059          if (iter == mappings.end()) result.Error("there is no map entry with that index");          result.Add("INSTRUMENT_FILE", instrumentFileName);
2060          else { // found          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2061              result.Add("NAME", iter->second.Name);          String instrumentName;
2062              result.Add("ENGINE_NAME", iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2063              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          if (pEngine) {
2064              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              if (pEngine->GetInstrumentManager()) {
2065              String instrumentName;                  InstrumentManager::instrument_id_t instrID;
2066              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);                  instrID.FileName = entry.InstrumentFile;
2067              if (pEngine) {                  instrID.Index    = entry.InstrumentIndex;
2068                  if (pEngine->GetInstrumentManager()) {                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                     InstrumentManager::instrument_id_t instrID;  
                     instrID.FileName = iter->second.InstrumentFile;  
                     instrID.Index    = iter->second.InstrumentIndex;  
                     instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);  
                 }  
                 EngineFactory::Destroy(pEngine);  
2069              }              }
2070              result.Add("INSTRUMENT_NAME", instrumentName);              EngineFactory::Destroy(pEngine);
2071              switch (iter->second.LoadMode) {          }
2072                  case MidiInstrumentMapper::ON_DEMAND:          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2073                      result.Add("LOAD_MODE", "ON_DEMAND");          switch (entry.LoadMode) {
2074                      break;              case MidiInstrumentMapper::ON_DEMAND:
2075                  case MidiInstrumentMapper::ON_DEMAND_HOLD:                  result.Add("LOAD_MODE", "ON_DEMAND");
2076                      result.Add("LOAD_MODE", "ON_DEMAND_HOLD");                  break;
2077                      break;              case MidiInstrumentMapper::ON_DEMAND_HOLD:
2078                  case MidiInstrumentMapper::PERSISTENT:                  result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2079                      result.Add("LOAD_MODE", "PERSISTENT");                  break;
2080                      break;              case MidiInstrumentMapper::PERSISTENT:
2081                  default:                  result.Add("LOAD_MODE", "PERSISTENT");
2082                      throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");                  break;
2083              }              default:
2084              result.Add("VOLUME", iter->second.Volume);                  throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2085          }          }
2086            result.Add("VOLUME", entry.Volume);
2087      } catch (Exception e) {      } catch (Exception e) {
2088          result.Error(e);          result.Error(e);
2089      }      }
# Line 1698  String LSCPServer::ListMidiInstrumentMap Line 2100  String LSCPServer::ListMidiInstrumentMap
2100          for (; iter != mappings.end(); iter++) {          for (; iter != mappings.end(); iter++) {
2101              if (s.size()) s += ",";              if (s.size()) s += ",";
2102              s += "{" + ToString(MidiMapID) + ","              s += "{" + ToString(MidiMapID) + ","
2103                       + ToString((int(iter->first.midi_bank_msb) << 7) & int(iter->first.midi_bank_lsb)) + ","                       + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2104                       + ToString(int(iter->first.midi_prog)) + "}";                       + ToString(int(iter->first.midi_prog)) + "}";
2105          }          }
2106          result.Add(s);          result.Add(s);
# Line 1720  String LSCPServer::ListAllMidiInstrument Line 2122  String LSCPServer::ListAllMidiInstrument
2122              for (; iter != mappings.end(); iter++) {              for (; iter != mappings.end(); iter++) {
2123                  if (s.size()) s += ",";                  if (s.size()) s += ",";
2124                  s += "{" + ToString(maps[i]) + ","                  s += "{" + ToString(maps[i]) + ","
2125                           + ToString((int(iter->first.midi_bank_msb) << 7) & int(iter->first.midi_bank_lsb)) + ","                           + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2126                           + ToString(int(iter->first.midi_prog)) + "}";                           + ToString(int(iter->first.midi_prog)) + "}";
2127              }              }
2128          }          }
# Line 1821  String LSCPServer::GetMidiInstrumentMap( Line 2223  String LSCPServer::GetMidiInstrumentMap(
2223      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2224      LSCPResultSet result;      LSCPResultSet result;
2225      try {      try {
2226          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2227            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2228      } catch (Exception e) {      } catch (Exception e) {
2229          result.Error(e);          result.Error(e);
2230      }      }
# Line 1866  String LSCPServer::SetChannelMap(uint ui Line 2269  String LSCPServer::SetChannelMap(uint ui
2269      return result.Produce();      return result.Produce();
2270  }  }
2271    
2272    String LSCPServer::CreateFxSend(uint uiSamplerChannel, uint MidiCtrl, String Name) {
2273        dmsg(2,("LSCPServer: CreateFxSend()\n"));
2274        LSCPResultSet result;
2275        try {
2276            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2277    
2278            FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2279            if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2280    
2281            result = LSCPResultSet(pFxSend->Id()); // success
2282        } catch (Exception e) {
2283            result.Error(e);
2284        }
2285        return result.Produce();
2286    }
2287    
2288    String LSCPServer::DestroyFxSend(uint uiSamplerChannel, uint FxSendID) {
2289        dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2290        LSCPResultSet result;
2291        try {
2292            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2293    
2294            FxSend* pFxSend = NULL;
2295            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2296                if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2297                    pFxSend = pEngineChannel->GetFxSend(i);
2298                    break;
2299                }
2300            }
2301            if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2302            pEngineChannel->RemoveFxSend(pFxSend);
2303        } catch (Exception e) {
2304            result.Error(e);
2305        }
2306        return result.Produce();
2307    }
2308    
2309    String LSCPServer::GetFxSends(uint uiSamplerChannel) {
2310        dmsg(2,("LSCPServer: GetFxSends()\n"));
2311        LSCPResultSet result;
2312        try {
2313            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2314    
2315            result.Add(pEngineChannel->GetFxSendCount());
2316        } catch (Exception e) {
2317            result.Error(e);
2318        }
2319        return result.Produce();
2320    }
2321    
2322    String LSCPServer::ListFxSends(uint uiSamplerChannel) {
2323        dmsg(2,("LSCPServer: ListFxSends()\n"));
2324        LSCPResultSet result;
2325        String list;
2326        try {
2327            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2328    
2329            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2330                FxSend* pFxSend = pEngineChannel->GetFxSend(i);
2331                if (list != "") list += ",";
2332                list += ToString(pFxSend->Id());
2333            }
2334            result.Add(list);
2335        } catch (Exception e) {
2336            result.Error(e);
2337        }
2338        return result.Produce();
2339    }
2340    
2341    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2342        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2343    
2344        FxSend* pFxSend = NULL;
2345        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2346            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2347                pFxSend = pEngineChannel->GetFxSend(i);
2348                break;
2349            }
2350        }
2351        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2352        return pFxSend;
2353    }
2354    
2355    String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2356        dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2357        LSCPResultSet result;
2358        try {
2359            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2360            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2361    
2362            // gather audio routing informations
2363            String AudioRouting;
2364            for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
2365                if (AudioRouting != "") AudioRouting += ",";
2366                AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2367            }
2368    
2369            // success
2370            result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2371            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2372            result.Add("LEVEL", ToString(pFxSend->Level()));
2373            result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2374        } catch (Exception e) {
2375            result.Error(e);
2376        }
2377        return result.Produce();
2378    }
2379    
2380    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2381        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2382        LSCPResultSet result;
2383        try {
2384            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2385    
2386            pFxSend->SetName(Name);
2387            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2388        } catch (Exception e) {
2389            result.Error(e);
2390        }
2391        return result.Produce();
2392    }
2393    
2394    String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2395        dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2396        LSCPResultSet result;
2397        try {
2398            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2399    
2400            pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2401            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2402        } catch (Exception e) {
2403            result.Error(e);
2404        }
2405        return result.Produce();
2406    }
2407    
2408    String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2409        dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2410        LSCPResultSet result;
2411        try {
2412            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2413    
2414            pFxSend->SetMidiController(MidiController);
2415            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2416        } catch (Exception e) {
2417            result.Error(e);
2418        }
2419        return result.Produce();
2420    }
2421    
2422    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2423        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2424        LSCPResultSet result;
2425        try {
2426            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2427    
2428            pFxSend->SetLevel((float)dLevel);
2429            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2430        } catch (Exception e) {
2431            result.Error(e);
2432        }
2433        return result.Produce();
2434    }
2435    
2436    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2437        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2438        LSCPResultSet result;
2439        try {
2440            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2441            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2442            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2443            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2444            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2445            Engine* pEngine = pEngineChannel->GetEngine();
2446            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2447            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2448            InstrumentManager::instrument_id_t instrumentID;
2449            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2450            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2451            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2452        } catch (Exception e) {
2453            result.Error(e);
2454        }
2455        return result.Produce();
2456    }
2457    
2458  /**  /**
2459   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2460   */   */
# Line 1901  String LSCPServer::ResetSampler() { Line 2490  String LSCPServer::ResetSampler() {
2490   */   */
2491  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2492      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2493        const std::string description =
2494            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2495      LSCPResultSet result;      LSCPResultSet result;
2496      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2497      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2498      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2499    #if HAVE_SQLITE3
2500        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2501    #else
2502        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2503    #endif
2504    
2505        return result.Produce();
2506    }
2507    
2508    /**
2509     * Will be called by the parser to return the current number of all active streams.
2510     */
2511    String LSCPServer::GetTotalStreamCount() {
2512        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2513        LSCPResultSet result;
2514        result.Add(pSampler->GetDiskStreamCount());
2515      return result.Produce();      return result.Produce();
2516  }  }
2517    
# Line 1928  String LSCPServer::GetTotalVoiceCountMax Line 2535  String LSCPServer::GetTotalVoiceCountMax
2535      return result.Produce();      return result.Produce();
2536  }  }
2537    
2538    String LSCPServer::GetGlobalVolume() {
2539        LSCPResultSet result;
2540        result.Add(ToString(GLOBAL_VOLUME)); // see common/global.cpp
2541        return result.Produce();
2542    }
2543    
2544    String LSCPServer::SetGlobalVolume(double dVolume) {
2545        LSCPResultSet result;
2546        try {
2547            if (dVolume < 0) throw Exception("Volume may not be negative");
2548            GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2549            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2550        } catch (Exception e) {
2551            result.Error(e);
2552        }
2553        return result.Produce();
2554    }
2555    
2556    String LSCPServer::GetFileInstruments(String Filename) {
2557        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2558        LSCPResultSet result;
2559        try {
2560            VerifyFile(Filename);
2561        } catch (Exception e) {
2562            result.Error(e);
2563            return result.Produce();
2564        }
2565        // try to find a sampler engine that can handle the file
2566        bool bFound = false;
2567        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2568        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2569            Engine* pEngine = NULL;
2570            try {
2571                pEngine = EngineFactory::Create(engineTypes[i]);
2572                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2573                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2574                if (pManager) {
2575                    std::vector<InstrumentManager::instrument_id_t> IDs =
2576                        pManager->GetInstrumentFileContent(Filename);
2577                    // return the amount of instruments in the file
2578                    result.Add(IDs.size());
2579                    // no more need to ask other engine types
2580                    bFound = true;
2581                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2582            } catch (Exception e) {
2583                // NOOP, as exception is thrown if engine doesn't support file
2584            }
2585            if (pEngine) EngineFactory::Destroy(pEngine);
2586        }
2587    
2588        if (!bFound) result.Error("Unknown file format");
2589        return result.Produce();
2590    }
2591    
2592    String LSCPServer::ListFileInstruments(String Filename) {
2593        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2594        LSCPResultSet result;
2595        try {
2596            VerifyFile(Filename);
2597        } catch (Exception e) {
2598            result.Error(e);
2599            return result.Produce();
2600        }
2601        // try to find a sampler engine that can handle the file
2602        bool bFound = false;
2603        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2604        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2605            Engine* pEngine = NULL;
2606            try {
2607                pEngine = EngineFactory::Create(engineTypes[i]);
2608                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2609                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2610                if (pManager) {
2611                    std::vector<InstrumentManager::instrument_id_t> IDs =
2612                        pManager->GetInstrumentFileContent(Filename);
2613                    // return a list of IDs of the instruments in the file
2614                    String s;
2615                    for (int j = 0; j < IDs.size(); j++) {
2616                        if (s.size()) s += ",";
2617                        s += ToString(IDs[j].Index);
2618                    }
2619                    result.Add(s);
2620                    // no more need to ask other engine types
2621                    bFound = true;
2622                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2623            } catch (Exception e) {
2624                // NOOP, as exception is thrown if engine doesn't support file
2625            }
2626            if (pEngine) EngineFactory::Destroy(pEngine);
2627        }
2628    
2629        if (!bFound) result.Error("Unknown file format");
2630        return result.Produce();
2631    }
2632    
2633    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2634        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2635        LSCPResultSet result;
2636        try {
2637            VerifyFile(Filename);
2638        } catch (Exception e) {
2639            result.Error(e);
2640            return result.Produce();
2641        }
2642        InstrumentManager::instrument_id_t id;
2643        id.FileName = Filename;
2644        id.Index    = InstrumentID;
2645        // try to find a sampler engine that can handle the file
2646        bool bFound = false;
2647        bool bFatalErr = false;
2648        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2649        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2650            Engine* pEngine = NULL;
2651            try {
2652                pEngine = EngineFactory::Create(engineTypes[i]);
2653                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2654                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2655                if (pManager) {
2656                    // check if the instrument index is valid
2657                    // FIXME: this won't work if an engine only supports parts of the instrument file
2658                    std::vector<InstrumentManager::instrument_id_t> IDs =
2659                        pManager->GetInstrumentFileContent(Filename);
2660                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2661                        std::stringstream ss;
2662                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2663                        bFatalErr = true;
2664                        throw Exception(ss.str());
2665                    }
2666                    // get the info of the requested instrument
2667                    InstrumentManager::instrument_info_t info =
2668                        pManager->GetInstrumentInfo(id);
2669                    // return detailed informations about the file
2670                    result.Add("NAME", info.InstrumentName);
2671                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2672                    result.Add("FORMAT_VERSION", info.FormatVersion);
2673                    result.Add("PRODUCT", info.Product);
2674                    result.Add("ARTISTS", info.Artists);
2675                    // no more need to ask other engine types
2676                    bFound = true;
2677                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2678            } catch (Exception e) {
2679                // usually NOOP, as exception is thrown if engine doesn't support file
2680                if (bFatalErr) result.Error(e);
2681            }
2682            if (pEngine) EngineFactory::Destroy(pEngine);
2683        }
2684    
2685        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2686        return result.Produce();
2687    }
2688    
2689    void LSCPServer::VerifyFile(String Filename) {
2690        #if WIN32
2691        WIN32_FIND_DATA win32FileAttributeData;
2692        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2693        if (!res) {
2694            std::stringstream ss;
2695            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2696            throw Exception(ss.str());
2697        }
2698        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2699            throw Exception("Directory is specified");
2700        }
2701        #else
2702        struct stat statBuf;
2703        int res = stat(Filename.c_str(), &statBuf);
2704        if (res) {
2705            std::stringstream ss;
2706            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2707            throw Exception(ss.str());
2708        }
2709    
2710        if (S_ISDIR(statBuf.st_mode)) {
2711            throw Exception("Directory is specified");
2712        }
2713        #endif
2714    }
2715    
2716  /**  /**
2717   * 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
2718   * server for receiving event messages.   * server for receiving event messages.
# Line 1954  String LSCPServer::UnsubscribeNotificati Line 2739  String LSCPServer::UnsubscribeNotificati
2739      return result.Produce();      return result.Produce();
2740  }  }
2741    
2742  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2743                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2744  {      LSCPResultSet result;
2745      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2746      resultSet->Add(argc, argv);      try {
2747      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2748        } catch (Exception e) {
2749             result.Error(e);
2750        }
2751    #else
2752        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2753    #endif
2754        return result.Produce();
2755    }
2756    
2757    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2758        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2759        LSCPResultSet result;
2760    #if HAVE_SQLITE3
2761        try {
2762            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2763        } catch (Exception e) {
2764             result.Error(e);
2765        }
2766    #else
2767        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2768    #endif
2769        return result.Produce();
2770    }
2771    
2772    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2773        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2774        LSCPResultSet result;
2775    #if HAVE_SQLITE3
2776        try {
2777            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2778        } catch (Exception e) {
2779             result.Error(e);
2780        }
2781    #else
2782        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2783    #endif
2784        return result.Produce();
2785  }  }
2786    
2787  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2788        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2789      LSCPResultSet result;      LSCPResultSet result;
2790  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2791      char* zErrMsg = NULL;      try {
2792      sqlite3 *db;          String list;
2793      String selectStr = "SELECT " + query;          StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2794    
2795      int rc = sqlite3_open("linuxsampler.db", &db);          for (int i = 0; i < dirs->size(); i++) {
2796      if (rc == SQLITE_OK)              if (list != "") list += ",";
2797      {              list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2798              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);          }
2799    
2800            result.Add(list);
2801        } catch (Exception e) {
2802             result.Error(e);
2803      }      }
2804      if ( rc != SQLITE_OK )  #else
2805      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2806              result.Error(String(zErrMsg), rc);  #endif
2807        return result.Produce();
2808    }
2809    
2810    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2811        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2812        LSCPResultSet result;
2813    #if HAVE_SQLITE3
2814        try {
2815            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2816    
2817            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2818            result.Add("CREATED", info.Created);
2819            result.Add("MODIFIED", info.Modified);
2820        } catch (Exception e) {
2821             result.Error(e);
2822        }
2823    #else
2824        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2825    #endif
2826        return result.Produce();
2827    }
2828    
2829    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2830        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2831        LSCPResultSet result;
2832    #if HAVE_SQLITE3
2833        try {
2834            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2835        } catch (Exception e) {
2836             result.Error(e);
2837      }      }
     sqlite3_close(db);  
2838  #else  #else
2839      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2840  #endif  #endif
2841      return result.Produce();      return result.Produce();
2842  }  }
2843    
2844    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2845        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2846        LSCPResultSet result;
2847    #if HAVE_SQLITE3
2848        try {
2849            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2850        } catch (Exception e) {
2851             result.Error(e);
2852        }
2853    #else
2854        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2855    #endif
2856        return result.Produce();
2857    }
2858    
2859    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2860        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2861        LSCPResultSet result;
2862    #if HAVE_SQLITE3
2863        try {
2864            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2865        } catch (Exception e) {
2866             result.Error(e);
2867        }
2868    #else
2869        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2870    #endif
2871        return result.Produce();
2872    }
2873    
2874    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2875        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2876        LSCPResultSet result;
2877    #if HAVE_SQLITE3
2878        try {
2879            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2880        } catch (Exception e) {
2881             result.Error(e);
2882        }
2883    #else
2884        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2885    #endif
2886        return result.Produce();
2887    }
2888    
2889    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2890        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2891        LSCPResultSet result;
2892    #if HAVE_SQLITE3
2893        try {
2894            int id;
2895            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2896            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2897            if (bBackground) result = id;
2898        } catch (Exception e) {
2899             result.Error(e);
2900        }
2901    #else
2902        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2903    #endif
2904        return result.Produce();
2905    }
2906    
2907    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2908        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2909        LSCPResultSet result;
2910    #if HAVE_SQLITE3
2911        try {
2912            int id;
2913            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2914            if (ScanMode.compare("RECURSIVE") == 0) {
2915               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2916            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2917               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2918            } else if (ScanMode.compare("FLAT") == 0) {
2919               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2920            } else {
2921                throw Exception("Unknown scan mode: " + ScanMode);
2922            }
2923    
2924            if (bBackground) result = id;
2925        } catch (Exception e) {
2926             result.Error(e);
2927        }
2928    #else
2929        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2930    #endif
2931        return result.Produce();
2932    }
2933    
2934    String LSCPServer::RemoveDbInstrument(String Instr) {
2935        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2936        LSCPResultSet result;
2937    #if HAVE_SQLITE3
2938        try {
2939            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2940        } catch (Exception e) {
2941             result.Error(e);
2942        }
2943    #else
2944        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2945    #endif
2946        return result.Produce();
2947    }
2948    
2949    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2950        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2951        LSCPResultSet result;
2952    #if HAVE_SQLITE3
2953        try {
2954            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2955        } catch (Exception e) {
2956             result.Error(e);
2957        }
2958    #else
2959        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2960    #endif
2961        return result.Produce();
2962    }
2963    
2964    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2965        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2966        LSCPResultSet result;
2967    #if HAVE_SQLITE3
2968        try {
2969            String list;
2970            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2971    
2972            for (int i = 0; i < instrs->size(); i++) {
2973                if (list != "") list += ",";
2974                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2975            }
2976    
2977            result.Add(list);
2978        } catch (Exception e) {
2979             result.Error(e);
2980        }
2981    #else
2982        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2983    #endif
2984        return result.Produce();
2985    }
2986    
2987    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2988        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2989        LSCPResultSet result;
2990    #if HAVE_SQLITE3
2991        try {
2992            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2993    
2994            result.Add("INSTRUMENT_FILE", info.InstrFile);
2995            result.Add("INSTRUMENT_NR", info.InstrNr);
2996            result.Add("FORMAT_FAMILY", info.FormatFamily);
2997            result.Add("FORMAT_VERSION", info.FormatVersion);
2998            result.Add("SIZE", (int)info.Size);
2999            result.Add("CREATED", info.Created);
3000            result.Add("MODIFIED", info.Modified);
3001            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3002            result.Add("IS_DRUM", info.IsDrum);
3003            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3004            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3005            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3006        } catch (Exception e) {
3007             result.Error(e);
3008        }
3009    #else
3010        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3011    #endif
3012        return result.Produce();
3013    }
3014    
3015    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3016        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3017        LSCPResultSet result;
3018    #if HAVE_SQLITE3
3019        try {
3020            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3021    
3022            result.Add("FILES_TOTAL", job.FilesTotal);
3023            result.Add("FILES_SCANNED", job.FilesScanned);
3024            result.Add("SCANNING", job.Scanning);
3025            result.Add("STATUS", job.Status);
3026        } catch (Exception e) {
3027             result.Error(e);
3028        }
3029    #else
3030        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3031    #endif
3032        return result.Produce();
3033    }
3034    
3035    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3036        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3037        LSCPResultSet result;
3038    #if HAVE_SQLITE3
3039        try {
3040            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3041        } catch (Exception e) {
3042             result.Error(e);
3043        }
3044    #else
3045        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3046    #endif
3047        return result.Produce();
3048    }
3049    
3050    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3051        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3052        LSCPResultSet result;
3053    #if HAVE_SQLITE3
3054        try {
3055            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3056        } catch (Exception e) {
3057             result.Error(e);
3058        }
3059    #else
3060        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3061    #endif
3062        return result.Produce();
3063    }
3064    
3065    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3066        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3067        LSCPResultSet result;
3068    #if HAVE_SQLITE3
3069        try {
3070            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3071        } catch (Exception e) {
3072             result.Error(e);
3073        }
3074    #else
3075        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3076    #endif
3077        return result.Produce();
3078    }
3079    
3080    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3081        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3082        LSCPResultSet result;
3083    #if HAVE_SQLITE3
3084        try {
3085            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3086        } catch (Exception e) {
3087             result.Error(e);
3088        }
3089    #else
3090        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3091    #endif
3092        return result.Produce();
3093    }
3094    
3095    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3096        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3097        LSCPResultSet result;
3098    #if HAVE_SQLITE3
3099        try {
3100            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3101        } catch (Exception e) {
3102             result.Error(e);
3103        }
3104    #else
3105        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3106    #endif
3107        return result.Produce();
3108    }
3109    
3110    String LSCPServer::FindLostDbInstrumentFiles() {
3111        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3112        LSCPResultSet result;
3113    #if HAVE_SQLITE3
3114        try {
3115            String list;
3116            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3117    
3118            for (int i = 0; i < pLostFiles->size(); i++) {
3119                if (list != "") list += ",";
3120                list += "'" + pLostFiles->at(i) + "'";
3121            }
3122    
3123            result.Add(list);
3124        } catch (Exception e) {
3125             result.Error(e);
3126        }
3127    #else
3128        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3129    #endif
3130        return result.Produce();
3131    }
3132    
3133    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3134        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3135        LSCPResultSet result;
3136    #if HAVE_SQLITE3
3137        try {
3138            SearchQuery Query;
3139            std::map<String,String>::iterator iter;
3140            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3141                if (iter->first.compare("NAME") == 0) {
3142                    Query.Name = iter->second;
3143                } else if (iter->first.compare("CREATED") == 0) {
3144                    Query.SetCreated(iter->second);
3145                } else if (iter->first.compare("MODIFIED") == 0) {
3146                    Query.SetModified(iter->second);
3147                } else if (iter->first.compare("DESCRIPTION") == 0) {
3148                    Query.Description = iter->second;
3149                } else {
3150                    throw Exception("Unknown search criteria: " + iter->first);
3151                }
3152            }
3153    
3154            String list;
3155            StringListPtr pDirectories =
3156                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3157    
3158            for (int i = 0; i < pDirectories->size(); i++) {
3159                if (list != "") list += ",";
3160                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3161            }
3162    
3163            result.Add(list);
3164        } catch (Exception e) {
3165             result.Error(e);
3166        }
3167    #else
3168        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3169    #endif
3170        return result.Produce();
3171    }
3172    
3173    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3174        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3175        LSCPResultSet result;
3176    #if HAVE_SQLITE3
3177        try {
3178            SearchQuery Query;
3179            std::map<String,String>::iterator iter;
3180            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3181                if (iter->first.compare("NAME") == 0) {
3182                    Query.Name = iter->second;
3183                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3184                    Query.SetFormatFamilies(iter->second);
3185                } else if (iter->first.compare("SIZE") == 0) {
3186                    Query.SetSize(iter->second);
3187                } else if (iter->first.compare("CREATED") == 0) {
3188                    Query.SetCreated(iter->second);
3189                } else if (iter->first.compare("MODIFIED") == 0) {
3190                    Query.SetModified(iter->second);
3191                } else if (iter->first.compare("DESCRIPTION") == 0) {
3192                    Query.Description = iter->second;
3193                } else if (iter->first.compare("IS_DRUM") == 0) {
3194                    if (!strcasecmp(iter->second.c_str(), "true")) {
3195                        Query.InstrType = SearchQuery::DRUM;
3196                    } else {
3197                        Query.InstrType = SearchQuery::CHROMATIC;
3198                    }
3199                } else if (iter->first.compare("PRODUCT") == 0) {
3200                     Query.Product = iter->second;
3201                } else if (iter->first.compare("ARTISTS") == 0) {
3202                     Query.Artists = iter->second;
3203                } else if (iter->first.compare("KEYWORDS") == 0) {
3204                     Query.Keywords = iter->second;
3205                } else {
3206                    throw Exception("Unknown search criteria: " + iter->first);
3207                }
3208            }
3209    
3210            String list;
3211            StringListPtr pInstruments =
3212                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3213    
3214            for (int i = 0; i < pInstruments->size(); i++) {
3215                if (list != "") list += ",";
3216                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3217            }
3218    
3219            result.Add(list);
3220        } catch (Exception e) {
3221             result.Error(e);
3222        }
3223    #else
3224        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3225    #endif
3226        return result.Produce();
3227    }
3228    
3229    String LSCPServer::FormatInstrumentsDb() {
3230        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3231        LSCPResultSet result;
3232    #if HAVE_SQLITE3
3233        try {
3234            InstrumentsDb::GetInstrumentsDb()->Format();
3235        } catch (Exception e) {
3236             result.Error(e);
3237        }
3238    #else
3239        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3240    #endif
3241        return result.Produce();
3242    }
3243    
3244    
3245  /**  /**
3246   * 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
3247   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be
# Line 2003  String LSCPServer::SetEcho(yyparse_param Line 3260  String LSCPServer::SetEcho(yyparse_param
3260      }      }
3261      return result.Produce();      return result.Produce();
3262  }  }
3263    
3264    }

Legend:
Removed from v.981  
changed lines
  Added in v.1765

  ViewVC Help
Powered by ViewVC