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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1649 - (show annotations) (download)
Fri Jan 25 15:06:02 2008 UTC (16 years, 2 months ago) by nagata
File size: 122436 byte(s)
* added a new config option --enable-pthread-testcancel, which uses
pthread_testcancel() instead of asynchronous canceling (needed for OSX)

1 /***************************************************************************
2 * *
3 * LinuxSampler - modular, streaming capable sampler *
4 * *
5 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 * Copyright (C) 2005 - 2007 Christian Schoenebeck *
7 * *
8 * 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 *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this library; if not, write to the Free Software *
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21 * MA 02111-1307 USA *
22 ***************************************************************************/
23
24 #include "lscpserver.h"
25 #include "lscpresultset.h"
26 #include "lscpevent.h"
27
28 #if defined(WIN32)
29 #include <windows.h>
30 #else
31 #include <fcntl.h>
32 #endif
33
34 #if ! HAVE_SQLITE3
35 #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
36 #endif
37
38 #include "../engines/EngineFactory.h"
39 #include "../engines/EngineChannelFactory.h"
40 #include "../drivers/audio/AudioOutputDeviceFactory.h"
41 #include "../drivers/midi/MidiInputDeviceFactory.h"
42
43
44 /**
45 * Returns a copy of the given string where all special characters are
46 * replaced by LSCP escape sequences ("\xHH"). This function shall be used
47 * to escape LSCP response fields in case the respective response field is
48 * actually defined as using escape sequences in the LSCP specs.
49 *
50 * @e Caution: DO NOT use this function for escaping path based responses,
51 * use the Path class (src/common/Path.h) for this instead!
52 */
53 static String _escapeLscpResponse(String txt) {
54 for (int i = 0; i < txt.length(); i++) {
55 const char c = txt.c_str()[i];
56 if (
57 !(c >= '0' && c <= '9') &&
58 !(c >= 'a' && c <= 'z') &&
59 !(c >= 'A' && c <= 'Z') &&
60 !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
61 !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
62 !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
63 !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
64 !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
65 !(c == '@') && !(c == '[') && !(c == ']') &&
66 !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
67 !(c == '|') && !(c == '}') && !(c == '~')
68 ) {
69 // convert the "special" character into a "\xHH" LSCP escape sequence
70 char buf[5];
71 snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
72 txt.replace(i, 1, buf);
73 i += 3;
74 }
75 }
76 return txt;
77 }
78
79 /**
80 * Below are a few static members of the LSCPServer class.
81 * The big assumption here is that LSCPServer is going to remain a singleton.
82 * These members are used to support client connections.
83 * Class handles multiple connections at the same time using select() and non-blocking recv()
84 * Commands are processed by a single LSCPServer thread.
85 * Notifications are delivered either by the thread that originated them
86 * or (if the resultset is currently in progress) by the LSCPServer thread
87 * after the resultset was sent out.
88 * This makes sure that resultsets can not be interrupted by notifications.
89 * This also makes sure that the thread sending notification is not blocked
90 * by the LSCPServer thread.
91 */
92 fd_set LSCPServer::fdSet;
93 int LSCPServer::currentSocket = -1;
94 std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
95 std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
96 std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
97 std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
98 std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
99 Mutex LSCPServer::NotifyMutex = Mutex();
100 Mutex LSCPServer::NotifyBufferMutex = Mutex();
101 Mutex LSCPServer::SubscriptionMutex = Mutex();
102 Mutex LSCPServer::RTNotifyMutex = Mutex();
103
104 LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4) {
105 SocketAddress.sin_family = AF_INET;
106 SocketAddress.sin_addr.s_addr = addr;
107 SocketAddress.sin_port = port;
108 this->pSampler = pSampler;
109 LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_count, "AUDIO_OUTPUT_DEVICE_COUNT");
110 LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_info, "AUDIO_OUTPUT_DEVICE_INFO");
111 LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_count, "MIDI_INPUT_DEVICE_COUNT");
112 LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_info, "MIDI_INPUT_DEVICE_INFO");
113 LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");
114 LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");
115 LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
116 LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
117 LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
118 LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_count, "FX_SEND_COUNT");
119 LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_info, "FX_SEND_INFO");
120 LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");
121 LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
122 LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
123 LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
124 LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
125 LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
126 LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
127 LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
128 LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
129 LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
130 LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
131 LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
132 LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
133 hSocket = -1;
134 }
135
136 LSCPServer::~LSCPServer() {
137 #if defined(WIN32)
138 if (hSocket >= 0) closesocket(hSocket);
139 #else
140 if (hSocket >= 0) close(hSocket);
141 #endif
142 }
143
144 void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
145 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
146 }
147
148 void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
149 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
150 }
151
152 void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
153 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
154 }
155
156 void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
157 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
158 }
159
160 void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
161 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
162 }
163
164 void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
165 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
166 }
167
168 void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
169 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
170 }
171
172 void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
173 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
174 }
175
176 void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
177 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
178 }
179
180 void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
181 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
182 }
183
184 void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
185 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
186 }
187
188 void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
189 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
190 }
191
192 void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
193 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
194 }
195
196 #if HAVE_SQLITE3
197 void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
198 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
199 }
200
201 void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
202 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
203 }
204
205 void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
206 Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
207 NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
208 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
209 }
210
211 void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
212 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
213 }
214
215 void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
216 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
217 }
218
219 void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
220 Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
221 NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
222 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
223 }
224
225 void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
226 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
227 }
228 #endif // HAVE_SQLITE3
229
230
231 /**
232 * Blocks the calling thread until the LSCP Server is initialized and
233 * accepting socket connections, if the server is already initialized then
234 * this method will return immediately.
235 * @param TimeoutSeconds - optional: max. wait time in seconds
236 * (default: 0s)
237 * @param TimeoutNanoSeconds - optional: max wait time in nano seconds
238 * (default: 0ns)
239 * @returns 0 on success, a value less than 0 if timeout exceeded
240 */
241 int LSCPServer::WaitUntilInitialized(long TimeoutSeconds, long TimeoutNanoSeconds) {
242 return Initialized.WaitAndUnlockIf(false, TimeoutSeconds, TimeoutNanoSeconds);
243 }
244
245 int LSCPServer::Main() {
246 #if defined(WIN32)
247 WSADATA wsaData;
248 int iResult;
249 iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
250 if (iResult != 0) {
251 std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
252 exit(EXIT_FAILURE);
253 }
254 #endif
255 hSocket = socket(AF_INET, SOCK_STREAM, 0);
256 if (hSocket < 0) {
257 std::cerr << "LSCPServer: Could not create server socket." << std::endl;
258 //return -1;
259 exit(EXIT_FAILURE);
260 }
261
262 if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
263 std::cerr << "LSCPServer: Could not bind server socket, retrying for " << ToString(LSCP_SERVER_BIND_TIMEOUT) << " seconds...";
264 for (int trial = 0; true; trial++) { // retry for LSCP_SERVER_BIND_TIMEOUT seconds
265 if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
266 if (trial > LSCP_SERVER_BIND_TIMEOUT) {
267 std::cerr << "gave up!" << std::endl;
268 #if defined(WIN32)
269 closesocket(hSocket);
270 #else
271 close(hSocket);
272 #endif
273 //return -1;
274 exit(EXIT_FAILURE);
275 }
276 else sleep(1); // sleep 1s
277 }
278 else break; // success
279 }
280 }
281
282 listen(hSocket, 1);
283 Initialized.Set(true);
284
285 // Registering event listeners
286 pSampler->AddChannelCountListener(&eventHandler);
287 pSampler->AddAudioDeviceCountListener(&eventHandler);
288 pSampler->AddMidiDeviceCountListener(&eventHandler);
289 pSampler->AddVoiceCountListener(&eventHandler);
290 pSampler->AddStreamCountListener(&eventHandler);
291 pSampler->AddBufferFillListener(&eventHandler);
292 pSampler->AddTotalStreamCountListener(&eventHandler);
293 pSampler->AddTotalVoiceCountListener(&eventHandler);
294 pSampler->AddFxSendCountListener(&eventHandler);
295 MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
296 MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
297 MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
298 MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
299 #if HAVE_SQLITE3
300 InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
301 #endif
302 // now wait for client connections and handle their requests
303 sockaddr_in client;
304 int length = sizeof(client);
305 FD_ZERO(&fdSet);
306 FD_SET(hSocket, &fdSet);
307 int maxSessions = hSocket;
308
309 timeval timeout;
310
311 while (true) {
312 #if CONFIG_PTHREAD_TESTCANCEL
313 TestCancel();
314 #endif
315 // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
316 {
317 std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
318 std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
319 std::set<EngineChannel*>::iterator itEnd = engineChannels.end();
320 for (; itEngineChannel != itEnd; ++itEngineChannel) {
321 if ((*itEngineChannel)->StatusChanged()) {
322 SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));
323 }
324
325 for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
326 FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
327 if(fxs != NULL && fxs->IsInfoChanged()) {
328 int chn = (*itEngineChannel)->iSamplerChannelIndex;
329 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
330 fxs->SetInfoChanged(false);
331 }
332 }
333 }
334 }
335
336 //Now let's deliver late notifies (if any)
337 NotifyBufferMutex.Lock();
338 for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
339 #ifdef MSG_NOSIGNAL
340 send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);
341 #else
342 send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
343 #endif
344 }
345 bufferedNotifies.clear();
346 NotifyBufferMutex.Unlock();
347
348 fd_set selectSet = fdSet;
349 timeout.tv_sec = 0;
350 timeout.tv_usec = 100000;
351
352 int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
353
354 if (retval == 0)
355 continue; //Nothing try again
356 if (retval == -1) {
357 std::cerr << "LSCPServer: Socket select error." << std::endl;
358 #if defined(WIN32)
359 closesocket(hSocket);
360 #else
361 close(hSocket);
362 #endif
363 exit(EXIT_FAILURE);
364 }
365
366 //Accept new connections now (if any)
367 if (FD_ISSET(hSocket, &selectSet)) {
368 int socket = accept(hSocket, (sockaddr*) &client, (socklen_t*) &length);
369 if (socket < 0) {
370 std::cerr << "LSCPServer: Client connection failed." << std::endl;
371 exit(EXIT_FAILURE);
372 }
373
374 #if defined(WIN32)
375 u_long nonblock_io = 1;
376 if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
377 std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
378 exit(EXIT_FAILURE);
379 }
380 #else
381 if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
382 std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
383 exit(EXIT_FAILURE);
384 }
385 #endif
386
387 // Parser initialization
388 yyparse_param_t yyparse_param;
389 yyparse_param.pServer = this;
390 yyparse_param.hSession = socket;
391
392 Sessions.push_back(yyparse_param);
393 FD_SET(socket, &fdSet);
394 if (socket > maxSessions)
395 maxSessions = socket;
396 dmsg(1,("LSCPServer: Client connection established on socket:%d.\n", socket));
397 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection established on socket", socket));
398 continue; //Maybe this was the only selected socket, better select again
399 }
400
401 //Something was selected and it was not the hSocket, so it must be some command(s) coming.
402 for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {
403 if (FD_ISSET((*iter).hSession, &selectSet)) { //Was it this socket?
404 if (GetLSCPCommand(iter)) { //Have we read the entire command?
405 dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));
406 int dummy; // just a temporary hack to fulfill the restart() function prototype
407 restart(NULL, dummy); // restart the 'scanner'
408 currentSocket = (*iter).hSession; //a hack
409 itCurrentSession = iter; // another hack
410 dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
411 if ((*iter).bVerbose) { // if echo mode enabled
412 AnswerClient(bufferedCommands[currentSocket]);
413 }
414 int result = yyparse(&(*iter));
415 currentSocket = -1; //continuation of a hack
416 itCurrentSession = Sessions.end(); // hack as well
417 dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
418 if (result == LSCP_QUIT) { //Was it a quit command by any chance?
419 CloseConnection(iter);
420 }
421 }
422 //socket may have been closed, iter may be invalid, get out of the loop for now.
423 //we'll be back if there is data.
424 break;
425 }
426 }
427 }
428 }
429
430 void LSCPServer::CloseConnection( std::vector<yyparse_param_t>::iterator iter ) {
431 int socket = (*iter).hSession;
432 dmsg(1,("LSCPServer: Client connection terminated on socket:%d.\n",socket));
433 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
434 Sessions.erase(iter);
435 FD_CLR(socket, &fdSet);
436 SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)
437 for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {
438 iter->second.remove(socket);
439 }
440 SubscriptionMutex.Unlock();
441 NotifyMutex.Lock();
442 bufferedCommands.erase(socket);
443 bufferedNotifies.erase(socket);
444 #if defined(WIN32)
445 closesocket(socket);
446 #else
447 close(socket);
448 #endif
449 NotifyMutex.Unlock();
450 }
451
452 void LSCPServer::LockRTNotify() {
453 RTNotifyMutex.Lock();
454 }
455
456 void LSCPServer::UnlockRTNotify() {
457 RTNotifyMutex.Unlock();
458 }
459
460 int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
461 int subs = 0;
462 SubscriptionMutex.Lock();
463 for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();
464 iter != events.end(); iter++)
465 {
466 subs += eventSubscriptions.count(*iter);
467 }
468 SubscriptionMutex.Unlock();
469 return subs;
470 }
471
472 void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
473 SubscriptionMutex.Lock();
474 if (eventSubscriptions.count(event.GetType()) == 0) {
475 SubscriptionMutex.Unlock(); //Nobody is subscribed to this event
476 return;
477 }
478 std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
479 std::list<int>::iterator end = eventSubscriptions[event.GetType()].end();
480 String notify = event.Produce();
481
482 while (true) {
483 if (NotifyMutex.Trylock()) {
484 for(;iter != end; iter++)
485 #ifdef MSG_NOSIGNAL
486 send(*iter, notify.c_str(), notify.size(), MSG_NOSIGNAL);
487 #else
488 send(*iter, notify.c_str(), notify.size(), 0);
489 #endif
490 NotifyMutex.Unlock();
491 break;
492 } else {
493 if (NotifyBufferMutex.Trylock()) {
494 for(;iter != end; iter++)
495 bufferedNotifies[*iter] += notify;
496 NotifyBufferMutex.Unlock();
497 break;
498 }
499 }
500 }
501 SubscriptionMutex.Unlock();
502 }
503
504 extern int GetLSCPCommand( void *buf, int max_size ) {
505 String command = LSCPServer::bufferedCommands[LSCPServer::currentSocket];
506 if (command.size() == 0) { //Parser wants input but we have nothing.
507 strcpy((char*) buf, "\n"); //So give it an empty command
508 return 1; //to keep it happy.
509 }
510
511 if (max_size < command.size()) {
512 std::cerr << "getLSCPCommand: Flex buffer too small, ignoring the command." << std::endl;
513 return 0; //This will never happen
514 }
515
516 strcpy((char*) buf, command.c_str());
517 LSCPServer::bufferedCommands.erase(LSCPServer::currentSocket);
518 return command.size();
519 }
520
521 extern yyparse_param_t* GetCurrentYaccSession() {
522 return &(*itCurrentSession);
523 }
524
525 /**
526 * Will be called to try to read the command from the socket
527 * If command is read, it will return true. Otherwise false is returned.
528 * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.
529 */
530 bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {
531 int socket = (*iter).hSession;
532 char c;
533 int i = 0;
534 while (true) {
535 #if defined(WIN32)
536 int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
537 #else
538 int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
539 #endif
540 if (result == 0) { //socket was selected, so 0 here means client has closed the connection
541 CloseConnection(iter);
542 break;
543 }
544 if (result == 1) {
545 if (c == '\r')
546 continue; //Ignore CR
547 if (c == '\n') {
548 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
549 bufferedCommands[socket] += "\r\n";
550 return true; //Complete command was read
551 }
552 bufferedCommands[socket] += c;
553 }
554 #if defined(WIN32)
555 if (result == SOCKET_ERROR) {
556 int wsa_lasterror = WSAGetLastError();
557 if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
558 return false;
559 dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
560 CloseConnection(iter);
561 break;
562 }
563 #else
564 if (result == -1) {
565 if (errno == EAGAIN) //Would block, try again later.
566 return false;
567 switch(errno) {
568 case EBADF:
569 dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
570 break;
571 case ECONNREFUSED:
572 dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
573 break;
574 case ENOTCONN:
575 dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));
576 break;
577 case ENOTSOCK:
578 dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
579 break;
580 case EAGAIN:
581 dmsg(2,("LSCPScanner: The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.\n"));
582 break;
583 case EINTR:
584 dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
585 break;
586 case EFAULT:
587 dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
588 break;
589 case EINVAL:
590 dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
591 break;
592 case ENOMEM:
593 dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
594 break;
595 default:
596 dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
597 break;
598 }
599 CloseConnection(iter);
600 break;
601 }
602 #endif
603 }
604 return false;
605 }
606
607 /**
608 * Will be called by the parser whenever it wants to send an answer to the
609 * client / frontend.
610 *
611 * @param ReturnMessage - message that will be send to the client
612 */
613 void LSCPServer::AnswerClient(String ReturnMessage) {
614 dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));
615 if (currentSocket != -1) {
616 NotifyMutex.Lock();
617 #ifdef MSG_NOSIGNAL
618 send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
619 #else
620 send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
621 #endif
622 NotifyMutex.Unlock();
623 }
624 }
625
626 /**
627 * Find a created audio output device index.
628 */
629 int LSCPServer::GetAudioOutputDeviceIndex ( AudioOutputDevice *pDevice )
630 {
631 // Search for the created device to get its index
632 std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
633 std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
634 for (; iter != devices.end(); iter++) {
635 if (iter->second == pDevice)
636 return iter->first;
637 }
638 // Not found.
639 return -1;
640 }
641
642 /**
643 * Find a created midi input device index.
644 */
645 int LSCPServer::GetMidiInputDeviceIndex ( MidiInputDevice *pDevice )
646 {
647 // Search for the created device to get its index
648 std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
649 std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
650 for (; iter != devices.end(); iter++) {
651 if (iter->second == pDevice)
652 return iter->first;
653 }
654 // Not found.
655 return -1;
656 }
657
658 String LSCPServer::CreateAudioOutputDevice(String Driver, std::map<String,String> Parameters) {
659 dmsg(2,("LSCPServer: CreateAudioOutputDevice(Driver=%s)\n", Driver.c_str()));
660 LSCPResultSet result;
661 try {
662 AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);
663 // search for the created device to get its index
664 int index = GetAudioOutputDeviceIndex(pDevice);
665 if (index == -1) throw Exception("Internal error: could not find created audio output device.");
666 result = index; // success
667 }
668 catch (Exception e) {
669 result.Error(e);
670 }
671 return result.Produce();
672 }
673
674 String LSCPServer::CreateMidiInputDevice(String Driver, std::map<String,String> Parameters) {
675 dmsg(2,("LSCPServer: CreateMidiInputDevice(Driver=%s)\n", Driver.c_str()));
676 LSCPResultSet result;
677 try {
678 MidiInputDevice* pDevice = pSampler->CreateMidiInputDevice(Driver, Parameters);
679 // search for the created device to get its index
680 int index = GetMidiInputDeviceIndex(pDevice);
681 if (index == -1) throw Exception("Internal error: could not find created midi input device.");
682 result = index; // success
683 }
684 catch (Exception e) {
685 result.Error(e);
686 }
687 return result.Produce();
688 }
689
690 String LSCPServer::DestroyAudioOutputDevice(uint DeviceIndex) {
691 dmsg(2,("LSCPServer: DestroyAudioOutputDevice(DeviceIndex=%d)\n", DeviceIndex));
692 LSCPResultSet result;
693 try {
694 std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
695 if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
696 AudioOutputDevice* pDevice = devices[DeviceIndex];
697 pSampler->DestroyAudioOutputDevice(pDevice);
698 }
699 catch (Exception e) {
700 result.Error(e);
701 }
702 return result.Produce();
703 }
704
705 String LSCPServer::DestroyMidiInputDevice(uint DeviceIndex) {
706 dmsg(2,("LSCPServer: DestroyMidiInputDevice(DeviceIndex=%d)\n", DeviceIndex));
707 LSCPResultSet result;
708 try {
709 std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
710 if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
711 MidiInputDevice* pDevice = devices[DeviceIndex];
712 pSampler->DestroyMidiInputDevice(pDevice);
713 }
714 catch (Exception e) {
715 result.Error(e);
716 }
717 return result.Produce();
718 }
719
720 EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
721 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
722 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
723
724 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
725 if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
726
727 return pEngineChannel;
728 }
729
730 /**
731 * Will be called by the parser to load an instrument.
732 */
733 String LSCPServer::LoadInstrument(String Filename, uint uiInstrument, uint uiSamplerChannel, bool bBackground) {
734 dmsg(2,("LSCPServer: LoadInstrument(Filename=%s,Instrument=%d,SamplerChannel=%d)\n", Filename.c_str(), uiInstrument, uiSamplerChannel));
735 LSCPResultSet result;
736 try {
737 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
738 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
739 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
740 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel yet");
741 if (!pSamplerChannel->GetAudioOutputDevice())
742 throw Exception("No audio output device connected to sampler channel");
743 if (bBackground) {
744 InstrumentManager::instrument_id_t id;
745 id.FileName = Filename;
746 id.Index = uiInstrument;
747 InstrumentManager::LoadInstrumentInBackground(id, pEngineChannel);
748 }
749 else {
750 // tell the engine channel which instrument to load
751 pEngineChannel->PrepareLoadInstrument(Filename.c_str(), uiInstrument);
752 // actually start to load the instrument (blocks until completed)
753 pEngineChannel->LoadInstrument();
754 }
755 }
756 catch (Exception e) {
757 result.Error(e);
758 }
759 return result.Produce();
760 }
761
762 /**
763 * Will be called by the parser to assign a sampler engine type to a
764 * sampler channel.
765 */
766 String LSCPServer::SetEngineType(String EngineName, uint uiSamplerChannel) {
767 dmsg(2,("LSCPServer: SetEngineType(EngineName=%s,uiSamplerChannel=%d)\n", EngineName.c_str(), uiSamplerChannel));
768 LSCPResultSet result;
769 try {
770 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
771 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
772 LockRTNotify();
773 pSamplerChannel->SetEngineType(EngineName);
774 if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
775 UnlockRTNotify();
776 }
777 catch (Exception e) {
778 result.Error(e);
779 }
780 return result.Produce();
781 }
782
783 /**
784 * Will be called by the parser to get the amount of sampler channels.
785 */
786 String LSCPServer::GetChannels() {
787 dmsg(2,("LSCPServer: GetChannels()\n"));
788 LSCPResultSet result;
789 result.Add(pSampler->SamplerChannels());
790 return result.Produce();
791 }
792
793 /**
794 * Will be called by the parser to get the list of sampler channels.
795 */
796 String LSCPServer::ListChannels() {
797 dmsg(2,("LSCPServer: ListChannels()\n"));
798 String list;
799 std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
800 std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
801 for (; iter != channels.end(); iter++) {
802 if (list != "") list += ",";
803 list += ToString(iter->first);
804 }
805 LSCPResultSet result;
806 result.Add(list);
807 return result.Produce();
808 }
809
810 /**
811 * Will be called by the parser to add a sampler channel.
812 */
813 String LSCPServer::AddChannel() {
814 dmsg(2,("LSCPServer: AddChannel()\n"));
815 LockRTNotify();
816 SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();
817 UnlockRTNotify();
818 LSCPResultSet result(pSamplerChannel->Index());
819 return result.Produce();
820 }
821
822 /**
823 * Will be called by the parser to remove a sampler channel.
824 */
825 String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
826 dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
827 LSCPResultSet result;
828 LockRTNotify();
829 pSampler->RemoveSamplerChannel(uiSamplerChannel);
830 UnlockRTNotify();
831 return result.Produce();
832 }
833
834 /**
835 * Will be called by the parser to get the amount of all available engines.
836 */
837 String LSCPServer::GetAvailableEngines() {
838 dmsg(2,("LSCPServer: GetAvailableEngines()\n"));
839 LSCPResultSet result;
840 try {
841 int n = EngineFactory::AvailableEngineTypes().size();
842 result.Add(n);
843 }
844 catch (Exception e) {
845 result.Error(e);
846 }
847 return result.Produce();
848 }
849
850 /**
851 * Will be called by the parser to get a list of all available engines.
852 */
853 String LSCPServer::ListAvailableEngines() {
854 dmsg(2,("LSCPServer: ListAvailableEngines()\n"));
855 LSCPResultSet result;
856 try {
857 String s = EngineFactory::AvailableEngineTypesAsString();
858 result.Add(s);
859 }
860 catch (Exception e) {
861 result.Error(e);
862 }
863 return result.Produce();
864 }
865
866 /**
867 * Will be called by the parser to get descriptions for a particular
868 * sampler engine.
869 */
870 String LSCPServer::GetEngineInfo(String EngineName) {
871 dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
872 LSCPResultSet result;
873 LockRTNotify();
874 try {
875 Engine* pEngine = EngineFactory::Create(EngineName);
876 result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
877 result.Add("VERSION", pEngine->Version());
878 EngineFactory::Destroy(pEngine);
879 }
880 catch (Exception e) {
881 result.Error(e);
882 }
883 UnlockRTNotify();
884 return result.Produce();
885 }
886
887 /**
888 * Will be called by the parser to get informations about a particular
889 * sampler channel.
890 */
891 String LSCPServer::GetChannelInfo(uint uiSamplerChannel) {
892 dmsg(2,("LSCPServer: GetChannelInfo(SamplerChannel=%d)\n", uiSamplerChannel));
893 LSCPResultSet result;
894 try {
895 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
896 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
897 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
898
899 //Defaults values
900 String EngineName = "NONE";
901 float Volume = 0.0f;
902 String InstrumentFileName = "NONE";
903 String InstrumentName = "NONE";
904 int InstrumentIndex = -1;
905 int InstrumentStatus = -1;
906 int AudioOutputChannels = 0;
907 String AudioRouting;
908 int Mute = 0;
909 bool Solo = false;
910 String MidiInstrumentMap = "NONE";
911
912 if (pEngineChannel) {
913 EngineName = pEngineChannel->EngineName();
914 AudioOutputChannels = pEngineChannel->Channels();
915 Volume = pEngineChannel->Volume();
916 InstrumentStatus = pEngineChannel->InstrumentStatus();
917 InstrumentIndex = pEngineChannel->InstrumentIndex();
918 if (InstrumentIndex != -1) {
919 InstrumentFileName = pEngineChannel->InstrumentFileName();
920 InstrumentName = pEngineChannel->InstrumentName();
921 }
922 for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
923 if (AudioRouting != "") AudioRouting += ",";
924 AudioRouting += ToString(pEngineChannel->OutputChannel(chan));
925 }
926 Mute = pEngineChannel->GetMute();
927 Solo = pEngineChannel->GetSolo();
928 if (pEngineChannel->UsesNoMidiInstrumentMap())
929 MidiInstrumentMap = "NONE";
930 else if (pEngineChannel->UsesDefaultMidiInstrumentMap())
931 MidiInstrumentMap = "DEFAULT";
932 else
933 MidiInstrumentMap = ToString(pEngineChannel->GetMidiInstrumentMap());
934 }
935
936 result.Add("ENGINE_NAME", EngineName);
937 result.Add("VOLUME", Volume);
938
939 //Some not-so-hardcoded stuff to make GUI look good
940 result.Add("AUDIO_OUTPUT_DEVICE", GetAudioOutputDeviceIndex(pSamplerChannel->GetAudioOutputDevice()));
941 result.Add("AUDIO_OUTPUT_CHANNELS", AudioOutputChannels);
942 result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
943
944 result.Add("MIDI_INPUT_DEVICE", GetMidiInputDeviceIndex(pSamplerChannel->GetMidiInputDevice()));
945 result.Add("MIDI_INPUT_PORT", pSamplerChannel->GetMidiInputPort());
946 if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
947 else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
948
949 // convert the filename into the correct encoding as defined for LSCP
950 // (especially in terms of special characters -> escape sequences)
951 if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
952 #if WIN32
953 InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
954 #else
955 // assuming POSIX
956 InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
957 #endif
958 }
959
960 result.Add("INSTRUMENT_FILE", InstrumentFileName);
961 result.Add("INSTRUMENT_NR", InstrumentIndex);
962 result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
963 result.Add("INSTRUMENT_STATUS", InstrumentStatus);
964 result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
965 result.Add("SOLO", Solo);
966 result.Add("MIDI_INSTRUMENT_MAP", MidiInstrumentMap);
967 }
968 catch (Exception e) {
969 result.Error(e);
970 }
971 return result.Produce();
972 }
973
974 /**
975 * Will be called by the parser to get the amount of active voices on a
976 * particular sampler channel.
977 */
978 String LSCPServer::GetVoiceCount(uint uiSamplerChannel) {
979 dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
980 LSCPResultSet result;
981 try {
982 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
983 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
984 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
985 if (!pEngineChannel) throw Exception("No engine loaded on sampler channel");
986 if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
987 result.Add(pEngineChannel->GetEngine()->VoiceCount());
988 }
989 catch (Exception e) {
990 result.Error(e);
991 }
992 return result.Produce();
993 }
994
995 /**
996 * Will be called by the parser to get the amount of active disk streams on a
997 * particular sampler channel.
998 */
999 String LSCPServer::GetStreamCount(uint uiSamplerChannel) {
1000 dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1001 LSCPResultSet result;
1002 try {
1003 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1004 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1005 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1006 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1007 if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1008 result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1009 }
1010 catch (Exception e) {
1011 result.Error(e);
1012 }
1013 return result.Produce();
1014 }
1015
1016 /**
1017 * Will be called by the parser to get the buffer fill states of all disk
1018 * streams on a particular sampler channel.
1019 */
1020 String LSCPServer::GetBufferFill(fill_response_t ResponseType, uint uiSamplerChannel) {
1021 dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1022 LSCPResultSet result;
1023 try {
1024 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1025 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1026 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1027 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1028 if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1029 if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1030 else {
1031 switch (ResponseType) {
1032 case fill_response_bytes:
1033 result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillBytes());
1034 break;
1035 case fill_response_percentage:
1036 result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillPercentage());
1037 break;
1038 default:
1039 throw Exception("Unknown fill response type");
1040 }
1041 }
1042 }
1043 catch (Exception e) {
1044 result.Error(e);
1045 }
1046 return result.Produce();
1047 }
1048
1049 String LSCPServer::GetAvailableAudioOutputDrivers() {
1050 dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));
1051 LSCPResultSet result;
1052 try {
1053 int n = AudioOutputDeviceFactory::AvailableDrivers().size();
1054 result.Add(n);
1055 }
1056 catch (Exception e) {
1057 result.Error(e);
1058 }
1059 return result.Produce();
1060 }
1061
1062 String LSCPServer::ListAvailableAudioOutputDrivers() {
1063 dmsg(2,("LSCPServer: ListAvailableAudioOutputDrivers()\n"));
1064 LSCPResultSet result;
1065 try {
1066 String s = AudioOutputDeviceFactory::AvailableDriversAsString();
1067 result.Add(s);
1068 }
1069 catch (Exception e) {
1070 result.Error(e);
1071 }
1072 return result.Produce();
1073 }
1074
1075 String LSCPServer::GetAvailableMidiInputDrivers() {
1076 dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));
1077 LSCPResultSet result;
1078 try {
1079 int n = MidiInputDeviceFactory::AvailableDrivers().size();
1080 result.Add(n);
1081 }
1082 catch (Exception e) {
1083 result.Error(e);
1084 }
1085 return result.Produce();
1086 }
1087
1088 String LSCPServer::ListAvailableMidiInputDrivers() {
1089 dmsg(2,("LSCPServer: ListAvailableMidiInputDrivers()\n"));
1090 LSCPResultSet result;
1091 try {
1092 String s = MidiInputDeviceFactory::AvailableDriversAsString();
1093 result.Add(s);
1094 }
1095 catch (Exception e) {
1096 result.Error(e);
1097 }
1098 return result.Produce();
1099 }
1100
1101 String LSCPServer::GetMidiInputDriverInfo(String Driver) {
1102 dmsg(2,("LSCPServer: GetMidiInputDriverInfo(Driver=%s)\n",Driver.c_str()));
1103 LSCPResultSet result;
1104 try {
1105 result.Add("DESCRIPTION", MidiInputDeviceFactory::GetDriverDescription(Driver));
1106 result.Add("VERSION", MidiInputDeviceFactory::GetDriverVersion(Driver));
1107
1108 std::map<String,DeviceCreationParameter*> parameters = MidiInputDeviceFactory::GetAvailableDriverParameters(Driver);
1109 if (parameters.size()) { // if there are parameters defined for this driver
1110 String s;
1111 std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
1112 for (;iter != parameters.end(); iter++) {
1113 if (s != "") s += ",";
1114 s += iter->first;
1115 }
1116 result.Add("PARAMETERS", s);
1117 }
1118 }
1119 catch (Exception e) {
1120 result.Error(e);
1121 }
1122 return result.Produce();
1123 }
1124
1125 String LSCPServer::GetAudioOutputDriverInfo(String Driver) {
1126 dmsg(2,("LSCPServer: GetAudioOutputDriverInfo(Driver=%s)\n",Driver.c_str()));
1127 LSCPResultSet result;
1128 try {
1129 result.Add("DESCRIPTION", AudioOutputDeviceFactory::GetDriverDescription(Driver));
1130 result.Add("VERSION", AudioOutputDeviceFactory::GetDriverVersion(Driver));
1131
1132 std::map<String,DeviceCreationParameter*> parameters = AudioOutputDeviceFactory::GetAvailableDriverParameters(Driver);
1133 if (parameters.size()) { // if there are parameters defined for this driver
1134 String s;
1135 std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
1136 for (;iter != parameters.end(); iter++) {
1137 if (s != "") s += ",";
1138 s += iter->first;
1139 }
1140 result.Add("PARAMETERS", s);
1141 }
1142 }
1143 catch (Exception e) {
1144 result.Error(e);
1145 }
1146 return result.Produce();
1147 }
1148
1149 String LSCPServer::GetMidiInputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
1150 dmsg(2,("LSCPServer: GetMidiInputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size()));
1151 LSCPResultSet result;
1152 try {
1153 DeviceCreationParameter* pParameter = MidiInputDeviceFactory::GetDriverParameter(Driver, Parameter);
1154 result.Add("TYPE", pParameter->Type());
1155 result.Add("DESCRIPTION", pParameter->Description());
1156 result.Add("MANDATORY", pParameter->Mandatory());
1157 result.Add("FIX", pParameter->Fix());
1158 result.Add("MULTIPLICITY", pParameter->Multiplicity());
1159 optional<String> oDepends = pParameter->Depends();
1160 optional<String> oDefault = pParameter->Default(DependencyList);
1161 optional<String> oRangeMin = pParameter->RangeMin(DependencyList);
1162 optional<String> oRangeMax = pParameter->RangeMax(DependencyList);
1163 optional<String> oPossibilities = pParameter->Possibilities(DependencyList);
1164 if (oDepends) result.Add("DEPENDS", *oDepends);
1165 if (oDefault) result.Add("DEFAULT", *oDefault);
1166 if (oRangeMin) result.Add("RANGE_MIN", *oRangeMin);
1167 if (oRangeMax) result.Add("RANGE_MAX", *oRangeMax);
1168 if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1169 }
1170 catch (Exception e) {
1171 result.Error(e);
1172 }
1173 return result.Produce();
1174 }
1175
1176 String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
1177 dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size()));
1178 LSCPResultSet result;
1179 try {
1180 DeviceCreationParameter* pParameter = AudioOutputDeviceFactory::GetDriverParameter(Driver, Parameter);
1181 result.Add("TYPE", pParameter->Type());
1182 result.Add("DESCRIPTION", pParameter->Description());
1183 result.Add("MANDATORY", pParameter->Mandatory());
1184 result.Add("FIX", pParameter->Fix());
1185 result.Add("MULTIPLICITY", pParameter->Multiplicity());
1186 optional<String> oDepends = pParameter->Depends();
1187 optional<String> oDefault = pParameter->Default(DependencyList);
1188 optional<String> oRangeMin = pParameter->RangeMin(DependencyList);
1189 optional<String> oRangeMax = pParameter->RangeMax(DependencyList);
1190 optional<String> oPossibilities = pParameter->Possibilities(DependencyList);
1191 if (oDepends) result.Add("DEPENDS", *oDepends);
1192 if (oDefault) result.Add("DEFAULT", *oDefault);
1193 if (oRangeMin) result.Add("RANGE_MIN", *oRangeMin);
1194 if (oRangeMax) result.Add("RANGE_MAX", *oRangeMax);
1195 if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1196 }
1197 catch (Exception e) {
1198 result.Error(e);
1199 }
1200 return result.Produce();
1201 }
1202
1203 String LSCPServer::GetAudioOutputDeviceCount() {
1204 dmsg(2,("LSCPServer: GetAudioOutputDeviceCount()\n"));
1205 LSCPResultSet result;
1206 try {
1207 uint count = pSampler->AudioOutputDevices();
1208 result.Add(count); // success
1209 }
1210 catch (Exception e) {
1211 result.Error(e);
1212 }
1213 return result.Produce();
1214 }
1215
1216 String LSCPServer::GetMidiInputDeviceCount() {
1217 dmsg(2,("LSCPServer: GetMidiInputDeviceCount()\n"));
1218 LSCPResultSet result;
1219 try {
1220 uint count = pSampler->MidiInputDevices();
1221 result.Add(count); // success
1222 }
1223 catch (Exception e) {
1224 result.Error(e);
1225 }
1226 return result.Produce();
1227 }
1228
1229 String LSCPServer::GetAudioOutputDevices() {
1230 dmsg(2,("LSCPServer: GetAudioOutputDevices()\n"));
1231 LSCPResultSet result;
1232 try {
1233 String s;
1234 std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1235 std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1236 for (; iter != devices.end(); iter++) {
1237 if (s != "") s += ",";
1238 s += ToString(iter->first);
1239 }
1240 result.Add(s);
1241 }
1242 catch (Exception e) {
1243 result.Error(e);
1244 }
1245 return result.Produce();
1246 }
1247
1248 String LSCPServer::GetMidiInputDevices() {
1249 dmsg(2,("LSCPServer: GetMidiInputDevices()\n"));
1250 LSCPResultSet result;
1251 try {
1252 String s;
1253 std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1254 std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
1255 for (; iter != devices.end(); iter++) {
1256 if (s != "") s += ",";
1257 s += ToString(iter->first);
1258 }
1259 result.Add(s);
1260 }
1261 catch (Exception e) {
1262 result.Error(e);
1263 }
1264 return result.Produce();
1265 }
1266
1267 String LSCPServer::GetAudioOutputDeviceInfo(uint DeviceIndex) {
1268 dmsg(2,("LSCPServer: GetAudioOutputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));
1269 LSCPResultSet result;
1270 try {
1271 std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1272 if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
1273 AudioOutputDevice* pDevice = devices[DeviceIndex];
1274 result.Add("DRIVER", pDevice->Driver());
1275 std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1276 std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
1277 for (; iter != parameters.end(); iter++) {
1278 result.Add(iter->first, iter->second->Value());
1279 }
1280 }
1281 catch (Exception e) {
1282 result.Error(e);
1283 }
1284 return result.Produce();
1285 }
1286
1287 String LSCPServer::GetMidiInputDeviceInfo(uint DeviceIndex) {
1288 dmsg(2,("LSCPServer: GetMidiInputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));
1289 LSCPResultSet result;
1290 try {
1291 std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1292 if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1293 MidiInputDevice* pDevice = devices[DeviceIndex];
1294 result.Add("DRIVER", pDevice->Driver());
1295 std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1296 std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
1297 for (; iter != parameters.end(); iter++) {
1298 result.Add(iter->first, iter->second->Value());
1299 }
1300 }
1301 catch (Exception e) {
1302 result.Error(e);
1303 }
1304 return result.Produce();
1305 }
1306 String LSCPServer::GetMidiInputPortInfo(uint DeviceIndex, uint PortIndex) {
1307 dmsg(2,("LSCPServer: GetMidiInputPortInfo(DeviceIndex=%d, PortIndex=%d)\n",DeviceIndex, PortIndex));
1308 LSCPResultSet result;
1309 try {
1310 // get MIDI input device
1311 std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1312 if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1313 MidiInputDevice* pDevice = devices[DeviceIndex];
1314
1315 // get MIDI port
1316 MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1317 if (!pMidiInputPort) throw Exception("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1318
1319 // return the values of all MIDI port parameters
1320 std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1321 std::map<String,DeviceRuntimeParameter*>::iterator iter = parameters.begin();
1322 for (; iter != parameters.end(); iter++) {
1323 result.Add(iter->first, iter->second->Value());
1324 }
1325 }
1326 catch (Exception e) {
1327 result.Error(e);
1328 }
1329 return result.Produce();
1330 }
1331
1332 String LSCPServer::GetAudioOutputChannelInfo(uint DeviceId, uint ChannelId) {
1333 dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%d,ChannelId)\n",DeviceId,ChannelId));
1334 LSCPResultSet result;
1335 try {
1336 // get audio output device
1337 std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1338 if (!devices.count(DeviceId)) throw Exception("There is no audio output device with index " + ToString(DeviceId) + ".");
1339 AudioOutputDevice* pDevice = devices[DeviceId];
1340
1341 // get audio channel
1342 AudioChannel* pChannel = pDevice->Channel(ChannelId);
1343 if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1344
1345 // return the values of all audio channel parameters
1346 std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1347 std::map<String,DeviceRuntimeParameter*>::iterator iter = parameters.begin();
1348 for (; iter != parameters.end(); iter++) {
1349 result.Add(iter->first, iter->second->Value());
1350 }
1351 }
1352 catch (Exception e) {
1353 result.Error(e);
1354 }
1355 return result.Produce();
1356 }
1357
1358 String LSCPServer::GetMidiInputPortParameterInfo(uint DeviceId, uint PortId, String ParameterName) {
1359 dmsg(2,("LSCPServer: GetMidiInputPortParameterInfo(DeviceId=%d,PortId=%d,ParameterName=%s)\n",DeviceId,PortId,ParameterName.c_str()));
1360 LSCPResultSet result;
1361 try {
1362 // get MIDI input device
1363 std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1364 if (!devices.count(DeviceId)) throw Exception("There is no midi input device with index " + ToString(DeviceId) + ".");
1365 MidiInputDevice* pDevice = devices[DeviceId];
1366
1367 // get midi port
1368 MidiInputPort* pPort = pDevice->GetPort(PortId);
1369 if (!pPort) throw Exception("Midi input device does not have port " + ToString(PortId) + ".");
1370
1371 // get desired port parameter
1372 std::map<String,DeviceRuntimeParameter*> parameters = pPort->PortParameters();
1373 if (!parameters.count(ParameterName)) throw Exception("Midi port does not provide a parameter '" + ParameterName + "'.");
1374 DeviceRuntimeParameter* pParameter = parameters[ParameterName];
1375
1376 // return all fields of this audio channel parameter
1377 result.Add("TYPE", pParameter->Type());
1378 result.Add("DESCRIPTION", pParameter->Description());
1379 result.Add("FIX", pParameter->Fix());
1380 result.Add("MULTIPLICITY", pParameter->Multiplicity());
1381 if (pParameter->RangeMin()) result.Add("RANGE_MIN", *pParameter->RangeMin());
1382 if (pParameter->RangeMax()) result.Add("RANGE_MAX", *pParameter->RangeMax());
1383 if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
1384 }
1385 catch (Exception e) {
1386 result.Error(e);
1387 }
1388 return result.Produce();
1389 }
1390
1391 String LSCPServer::GetAudioOutputChannelParameterInfo(uint DeviceId, uint ChannelId, String ParameterName) {
1392 dmsg(2,("LSCPServer: GetAudioOutputChannelParameterInfo(DeviceId=%d,ChannelId=%d,ParameterName=%s)\n",DeviceId,ChannelId,ParameterName.c_str()));
1393 LSCPResultSet result;
1394 try {
1395 // get audio output device
1396 std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1397 if (!devices.count(DeviceId)) throw Exception("There is no audio output device with index " + ToString(DeviceId) + ".");
1398 AudioOutputDevice* pDevice = devices[DeviceId];
1399
1400 // get audio channel
1401 AudioChannel* pChannel = pDevice->Channel(ChannelId);
1402 if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1403
1404 // get desired audio channel parameter
1405 std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1406 if (!parameters.count(ParameterName)) throw Exception("Audio channel does not provide a parameter '" + ParameterName + "'.");
1407 DeviceRuntimeParameter* pParameter = parameters[ParameterName];
1408
1409 // return all fields of this audio channel parameter
1410 result.Add("TYPE", pParameter->Type());
1411 result.Add("DESCRIPTION", pParameter->Description());
1412 result.Add("FIX", pParameter->Fix());
1413 result.Add("MULTIPLICITY", pParameter->Multiplicity());
1414 if (pParameter->RangeMin()) result.Add("RANGE_MIN", *pParameter->RangeMin());
1415 if (pParameter->RangeMax()) result.Add("RANGE_MAX", *pParameter->RangeMax());
1416 if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
1417 }
1418 catch (Exception e) {
1419 result.Error(e);
1420 }
1421 return result.Produce();
1422 }
1423
1424 String LSCPServer::SetAudioOutputChannelParameter(uint DeviceId, uint ChannelId, String ParamKey, String ParamVal) {
1425 dmsg(2,("LSCPServer: SetAudioOutputChannelParameter(DeviceId=%d,ChannelId=%d,ParamKey=%s,ParamVal=%s)\n",DeviceId,ChannelId,ParamKey.c_str(),ParamVal.c_str()));
1426 LSCPResultSet result;
1427 try {
1428 // get audio output device
1429 std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1430 if (!devices.count(DeviceId)) throw Exception("There is no audio output device with index " + ToString(DeviceId) + ".");
1431 AudioOutputDevice* pDevice = devices[DeviceId];
1432
1433 // get audio channel
1434 AudioChannel* pChannel = pDevice->Channel(ChannelId);
1435 if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1436
1437 // get desired audio channel parameter
1438 std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1439 if (!parameters.count(ParamKey)) throw Exception("Audio channel does not provide a parameter '" + ParamKey + "'.");
1440 DeviceRuntimeParameter* pParameter = parameters[ParamKey];
1441
1442 // set new channel parameter value
1443 pParameter->SetValue(ParamVal);
1444 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceId));
1445 }
1446 catch (Exception e) {
1447 result.Error(e);
1448 }
1449 return result.Produce();
1450 }
1451
1452 String LSCPServer::SetAudioOutputDeviceParameter(uint DeviceIndex, String ParamKey, String ParamVal) {
1453 dmsg(2,("LSCPServer: SetAudioOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1454 LSCPResultSet result;
1455 try {
1456 std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1457 if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
1458 AudioOutputDevice* pDevice = devices[DeviceIndex];
1459 std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1460 if (!parameters.count(ParamKey)) throw Exception("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1461 parameters[ParamKey]->SetValue(ParamVal);
1462 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceIndex));
1463 }
1464 catch (Exception e) {
1465 result.Error(e);
1466 }
1467 return result.Produce();
1468 }
1469
1470 String LSCPServer::SetMidiInputDeviceParameter(uint DeviceIndex, String ParamKey, String ParamVal) {
1471 dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1472 LSCPResultSet result;
1473 try {
1474 std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1475 if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1476 MidiInputDevice* pDevice = devices[DeviceIndex];
1477 std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1478 if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1479 parameters[ParamKey]->SetValue(ParamVal);
1480 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1481 }
1482 catch (Exception e) {
1483 result.Error(e);
1484 }
1485 return result.Produce();
1486 }
1487
1488 String LSCPServer::SetMidiInputPortParameter(uint DeviceIndex, uint PortIndex, String ParamKey, String ParamVal) {
1489 dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1490 LSCPResultSet result;
1491 try {
1492 // get MIDI input device
1493 std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1494 if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1495 MidiInputDevice* pDevice = devices[DeviceIndex];
1496
1497 // get MIDI port
1498 MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1499 if (!pMidiInputPort) throw Exception("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1500
1501 // set port parameter value
1502 std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1503 if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");
1504 parameters[ParamKey]->SetValue(ParamVal);
1505 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1506 }
1507 catch (Exception e) {
1508 result.Error(e);
1509 }
1510 return result.Produce();
1511 }
1512
1513 /**
1514 * Will be called by the parser to change the audio output channel for
1515 * playback on a particular sampler channel.
1516 */
1517 String LSCPServer::SetAudioOutputChannel(uint ChannelAudioOutputChannel, uint AudioOutputDeviceInputChannel, uint uiSamplerChannel) {
1518 dmsg(2,("LSCPServer: SetAudioOutputChannel(ChannelAudioOutputChannel=%d, AudioOutputDeviceInputChannel=%d, SamplerChannel=%d)\n",ChannelAudioOutputChannel,AudioOutputDeviceInputChannel,uiSamplerChannel));
1519 LSCPResultSet result;
1520 try {
1521 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1522 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1523 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1524 if (!pEngineChannel) throw Exception("No engine type yet assigned to sampler channel " + ToString(uiSamplerChannel));
1525 if (!pSamplerChannel->GetAudioOutputDevice()) throw Exception("No audio output device connected to sampler channel " + ToString(uiSamplerChannel));
1526 pEngineChannel->SetOutputChannel(ChannelAudioOutputChannel, AudioOutputDeviceInputChannel);
1527 }
1528 catch (Exception e) {
1529 result.Error(e);
1530 }
1531 return result.Produce();
1532 }
1533
1534 String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1535 dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1536 LSCPResultSet result;
1537 LockRTNotify();
1538 try {
1539 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1540 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1541 std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1542 if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1543 AudioOutputDevice* pDevice = devices[AudioDeviceId];
1544 pSamplerChannel->SetAudioOutputDevice(pDevice);
1545 }
1546 catch (Exception e) {
1547 result.Error(e);
1548 }
1549 UnlockRTNotify();
1550 return result.Produce();
1551 }
1552
1553 String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1554 dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1555 LSCPResultSet result;
1556 LockRTNotify();
1557 try {
1558 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1559 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1560 // Driver type name aliasing...
1561 if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1562 if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1563 // Check if there's one audio output device already created
1564 // for the intended audio driver type (AudioOutputDriver)...
1565 AudioOutputDevice *pDevice = NULL;
1566 std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1567 std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1568 for (; iter != devices.end(); iter++) {
1569 if ((iter->second)->Driver() == AudioOutputDriver) {
1570 pDevice = iter->second;
1571 break;
1572 }
1573 }
1574 // If it doesn't exist, create a new one with default parameters...
1575 if (pDevice == NULL) {
1576 std::map<String,String> params;
1577 pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1578 }
1579 // Must have a device...
1580 if (pDevice == NULL)
1581 throw Exception("Internal error: could not create audio output device.");
1582 // Set it as the current channel device...
1583 pSamplerChannel->SetAudioOutputDevice(pDevice);
1584 }
1585 catch (Exception e) {
1586 result.Error(e);
1587 }
1588 UnlockRTNotify();
1589 return result.Produce();
1590 }
1591
1592 String LSCPServer::SetMIDIInputPort(uint MIDIPort, uint uiSamplerChannel) {
1593 dmsg(2,("LSCPServer: SetMIDIInputPort(MIDIPort=%d, SamplerChannel=%d)\n",MIDIPort,uiSamplerChannel));
1594 LSCPResultSet result;
1595 try {
1596 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1597 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1598 pSamplerChannel->SetMidiInputPort(MIDIPort);
1599 }
1600 catch (Exception e) {
1601 result.Error(e);
1602 }
1603 return result.Produce();
1604 }
1605
1606 String LSCPServer::SetMIDIInputChannel(uint MIDIChannel, uint uiSamplerChannel) {
1607 dmsg(2,("LSCPServer: SetMIDIInputChannel(MIDIChannel=%d, SamplerChannel=%d)\n",MIDIChannel,uiSamplerChannel));
1608 LSCPResultSet result;
1609 try {
1610 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1611 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1612 pSamplerChannel->SetMidiInputChannel((midi_chan_t) MIDIChannel);
1613 }
1614 catch (Exception e) {
1615 result.Error(e);
1616 }
1617 return result.Produce();
1618 }
1619
1620 String LSCPServer::SetMIDIInputDevice(uint MIDIDeviceId, uint uiSamplerChannel) {
1621 dmsg(2,("LSCPServer: SetMIDIInputDevice(MIDIDeviceId=%d, SamplerChannel=%d)\n",MIDIDeviceId,uiSamplerChannel));
1622 LSCPResultSet result;
1623 try {
1624 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1625 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1626 std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1627 if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1628 MidiInputDevice* pDevice = devices[MIDIDeviceId];
1629 pSamplerChannel->SetMidiInputDevice(pDevice);
1630 }
1631 catch (Exception e) {
1632 result.Error(e);
1633 }
1634 return result.Produce();
1635 }
1636
1637 String LSCPServer::SetMIDIInputType(String MidiInputDriver, uint uiSamplerChannel) {
1638 dmsg(2,("LSCPServer: SetMIDIInputType(String MidiInputDriver=%s, SamplerChannel=%d)\n",MidiInputDriver.c_str(),uiSamplerChannel));
1639 LSCPResultSet result;
1640 try {
1641 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1642 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1643 // Driver type name aliasing...
1644 if (MidiInputDriver == "Alsa") MidiInputDriver = "ALSA";
1645 // Check if there's one MIDI input device already created
1646 // for the intended MIDI driver type (MidiInputDriver)...
1647 MidiInputDevice *pDevice = NULL;
1648 std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1649 std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
1650 for (; iter != devices.end(); iter++) {
1651 if ((iter->second)->Driver() == MidiInputDriver) {
1652 pDevice = iter->second;
1653 break;
1654 }
1655 }
1656 // If it doesn't exist, create a new one with default parameters...
1657 if (pDevice == NULL) {
1658 std::map<String,String> params;
1659 pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1660 // Make it with at least one initial port.
1661 std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1662 parameters["PORTS"]->SetValue("1");
1663 }
1664 // Must have a device...
1665 if (pDevice == NULL)
1666 throw Exception("Internal error: could not create MIDI input device.");
1667 // Set it as the current channel device...
1668 pSamplerChannel->SetMidiInputDevice(pDevice);
1669 }
1670 catch (Exception e) {
1671 result.Error(e);
1672 }
1673 return result.Produce();
1674 }
1675
1676 /**
1677 * Will be called by the parser to change the MIDI input device, port and channel on which
1678 * engine of a particular sampler channel should listen to.
1679 */
1680 String LSCPServer::SetMIDIInput(uint MIDIDeviceId, uint MIDIPort, uint MIDIChannel, uint uiSamplerChannel) {
1681 dmsg(2,("LSCPServer: SetMIDIInput(MIDIDeviceId=%d, MIDIPort=%d, MIDIChannel=%d, SamplerChannel=%d)\n", MIDIDeviceId, MIDIPort, MIDIChannel, uiSamplerChannel));
1682 LSCPResultSet result;
1683 try {
1684 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1685 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1686 std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1687 if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1688 MidiInputDevice* pDevice = devices[MIDIDeviceId];
1689 pSamplerChannel->SetMidiInput(pDevice, MIDIPort, (midi_chan_t) MIDIChannel);
1690 }
1691 catch (Exception e) {
1692 result.Error(e);
1693 }
1694 return result.Produce();
1695 }
1696
1697 /**
1698 * Will be called by the parser to change the global volume factor on a
1699 * particular sampler channel.
1700 */
1701 String LSCPServer::SetVolume(double dVolume, uint uiSamplerChannel) {
1702 dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1703 LSCPResultSet result;
1704 try {
1705 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1706 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1707 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1708 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1709 pEngineChannel->Volume(dVolume);
1710 }
1711 catch (Exception e) {
1712 result.Error(e);
1713 }
1714 return result.Produce();
1715 }
1716
1717 /**
1718 * Will be called by the parser to mute/unmute particular sampler channel.
1719 */
1720 String LSCPServer::SetChannelMute(bool bMute, uint uiSamplerChannel) {
1721 dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1722 LSCPResultSet result;
1723 try {
1724 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1725 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1726
1727 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1728 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1729
1730 if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1731 else pEngineChannel->SetMute(1);
1732 } catch (Exception e) {
1733 result.Error(e);
1734 }
1735 return result.Produce();
1736 }
1737
1738 /**
1739 * Will be called by the parser to solo particular sampler channel.
1740 */
1741 String LSCPServer::SetChannelSolo(bool bSolo, uint uiSamplerChannel) {
1742 dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1743 LSCPResultSet result;
1744 try {
1745 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1746 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1747
1748 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1749 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1750
1751 bool oldSolo = pEngineChannel->GetSolo();
1752 bool hadSoloChannel = HasSoloChannel();
1753
1754 pEngineChannel->SetSolo(bSolo);
1755
1756 if(!oldSolo && bSolo) {
1757 if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1758 if(!hadSoloChannel) MuteNonSoloChannels();
1759 }
1760
1761 if(oldSolo && !bSolo) {
1762 if(!HasSoloChannel()) UnmuteChannels();
1763 else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
1764 }
1765 } catch (Exception e) {
1766 result.Error(e);
1767 }
1768 return result.Produce();
1769 }
1770
1771 /**
1772 * Determines whether there is at least one solo channel in the channel list.
1773 *
1774 * @returns true if there is at least one solo channel in the channel list,
1775 * false otherwise.
1776 */
1777 bool LSCPServer::HasSoloChannel() {
1778 std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1779 std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1780 for (; iter != channels.end(); iter++) {
1781 EngineChannel* c = iter->second->GetEngineChannel();
1782 if(c && c->GetSolo()) return true;
1783 }
1784
1785 return false;
1786 }
1787
1788 /**
1789 * Mutes all unmuted non-solo channels. Notice that the channels are muted
1790 * with -1 which indicates that they are muted because of the presence
1791 * of a solo channel(s). Channels muted with -1 will be automatically unmuted
1792 * when there are no solo channels left.
1793 */
1794 void LSCPServer::MuteNonSoloChannels() {
1795 dmsg(2,("LSCPServer: MuteNonSoloChannels()\n"));
1796 std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1797 std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1798 for (; iter != channels.end(); iter++) {
1799 EngineChannel* c = iter->second->GetEngineChannel();
1800 if(c && !c->GetSolo() && !c->GetMute()) c->SetMute(-1);
1801 }
1802 }
1803
1804 /**
1805 * Unmutes all channels that are muted because of the presence
1806 * of a solo channel(s).
1807 */
1808 void LSCPServer::UnmuteChannels() {
1809 dmsg(2,("LSCPServer: UnmuteChannels()\n"));
1810 std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1811 std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1812 for (; iter != channels.end(); iter++) {
1813 EngineChannel* c = iter->second->GetEngineChannel();
1814 if(c && c->GetMute() == -1) c->SetMute(0);
1815 }
1816 }
1817
1818 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) {
1819 dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1820
1821 midi_prog_index_t idx;
1822 idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
1823 idx.midi_bank_lsb = MidiBank & 0x7f;
1824 idx.midi_prog = MidiProg;
1825
1826 MidiInstrumentMapper::entry_t entry;
1827 entry.EngineName = EngineType;
1828 entry.InstrumentFile = InstrumentFile;
1829 entry.InstrumentIndex = InstrumentIndex;
1830 entry.LoadMode = LoadMode;
1831 entry.Volume = Volume;
1832 entry.Name = Name;
1833
1834 LSCPResultSet result;
1835 try {
1836 // PERSISTENT mapping commands might block for a long time, so in
1837 // that case we add/replace the mapping in another thread in case
1838 // the NON_MODAL argument was supplied, non persistent mappings
1839 // should return immediately, so we don't need to do that for them
1840 bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
1841 MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
1842 } catch (Exception e) {
1843 result.Error(e);
1844 }
1845 return result.Produce();
1846 }
1847
1848 String LSCPServer::RemoveMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
1849 dmsg(2,("LSCPServer: RemoveMIDIInstrumentMapping()\n"));
1850
1851 midi_prog_index_t idx;
1852 idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
1853 idx.midi_bank_lsb = MidiBank & 0x7f;
1854 idx.midi_prog = MidiProg;
1855
1856 LSCPResultSet result;
1857 try {
1858 MidiInstrumentMapper::RemoveEntry(MidiMapID, idx);
1859 } catch (Exception e) {
1860 result.Error(e);
1861 }
1862 return result.Produce();
1863 }
1864
1865 String LSCPServer::GetMidiInstrumentMappings(uint MidiMapID) {
1866 dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
1867 LSCPResultSet result;
1868 try {
1869 result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());
1870 } catch (Exception e) {
1871 result.Error(e);
1872 }
1873 return result.Produce();
1874 }
1875
1876
1877 String LSCPServer::GetAllMidiInstrumentMappings() {
1878 dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
1879 LSCPResultSet result;
1880 std::vector<int> maps = MidiInstrumentMapper::Maps();
1881 int totalMappings = 0;
1882 for (int i = 0; i < maps.size(); i++) {
1883 try {
1884 totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();
1885 } catch (Exception e) { /*NOOP*/ }
1886 }
1887 result.Add(totalMappings);
1888 return result.Produce();
1889 }
1890
1891 String LSCPServer::GetMidiInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
1892 dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
1893 LSCPResultSet result;
1894 try {
1895 midi_prog_index_t idx;
1896 idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
1897 idx.midi_bank_lsb = MidiBank & 0x7f;
1898 idx.midi_prog = MidiProg;
1899
1900 std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);
1901 std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);
1902 if (iter == mappings.end()) result.Error("there is no map entry with that index");
1903 else { // found
1904
1905 // convert the filename into the correct encoding as defined for LSCP
1906 // (especially in terms of special characters -> escape sequences)
1907 #if WIN32
1908 const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1909 #else
1910 // assuming POSIX
1911 const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1912 #endif
1913
1914 result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1915 result.Add("ENGINE_NAME", iter->second.EngineName);
1916 result.Add("INSTRUMENT_FILE", instrumentFileName);
1917 result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1918 String instrumentName;
1919 Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
1920 if (pEngine) {
1921 if (pEngine->GetInstrumentManager()) {
1922 InstrumentManager::instrument_id_t instrID;
1923 instrID.FileName = iter->second.InstrumentFile;
1924 instrID.Index = iter->second.InstrumentIndex;
1925 instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
1926 }
1927 EngineFactory::Destroy(pEngine);
1928 }
1929 result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
1930 switch (iter->second.LoadMode) {
1931 case MidiInstrumentMapper::ON_DEMAND:
1932 result.Add("LOAD_MODE", "ON_DEMAND");
1933 break;
1934 case MidiInstrumentMapper::ON_DEMAND_HOLD:
1935 result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
1936 break;
1937 case MidiInstrumentMapper::PERSISTENT:
1938 result.Add("LOAD_MODE", "PERSISTENT");
1939 break;
1940 default:
1941 throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
1942 }
1943 result.Add("VOLUME", iter->second.Volume);
1944 }
1945 } catch (Exception e) {
1946 result.Error(e);
1947 }
1948 return result.Produce();
1949 }
1950
1951 String LSCPServer::ListMidiInstrumentMappings(uint MidiMapID) {
1952 dmsg(2,("LSCPServer: ListMidiInstrumentMappings()\n"));
1953 LSCPResultSet result;
1954 try {
1955 String s;
1956 std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);
1957 std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
1958 for (; iter != mappings.end(); iter++) {
1959 if (s.size()) s += ",";
1960 s += "{" + ToString(MidiMapID) + ","
1961 + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
1962 + ToString(int(iter->first.midi_prog)) + "}";
1963 }
1964 result.Add(s);
1965 } catch (Exception e) {
1966 result.Error(e);
1967 }
1968 return result.Produce();
1969 }
1970
1971 String LSCPServer::ListAllMidiInstrumentMappings() {
1972 dmsg(2,("LSCPServer: ListAllMidiInstrumentMappings()\n"));
1973 LSCPResultSet result;
1974 try {
1975 std::vector<int> maps = MidiInstrumentMapper::Maps();
1976 String s;
1977 for (int i = 0; i < maps.size(); i++) {
1978 std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(maps[i]);
1979 std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
1980 for (; iter != mappings.end(); iter++) {
1981 if (s.size()) s += ",";
1982 s += "{" + ToString(maps[i]) + ","
1983 + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
1984 + ToString(int(iter->first.midi_prog)) + "}";
1985 }
1986 }
1987 result.Add(s);
1988 } catch (Exception e) {
1989 result.Error(e);
1990 }
1991 return result.Produce();
1992 }
1993
1994 String LSCPServer::ClearMidiInstrumentMappings(uint MidiMapID) {
1995 dmsg(2,("LSCPServer: ClearMidiInstrumentMappings()\n"));
1996 LSCPResultSet result;
1997 try {
1998 MidiInstrumentMapper::RemoveAllEntries(MidiMapID);
1999 } catch (Exception e) {
2000 result.Error(e);
2001 }
2002 return result.Produce();
2003 }
2004
2005 String LSCPServer::ClearAllMidiInstrumentMappings() {
2006 dmsg(2,("LSCPServer: ClearAllMidiInstrumentMappings()\n"));
2007 LSCPResultSet result;
2008 try {
2009 std::vector<int> maps = MidiInstrumentMapper::Maps();
2010 for (int i = 0; i < maps.size(); i++)
2011 MidiInstrumentMapper::RemoveAllEntries(maps[i]);
2012 } catch (Exception e) {
2013 result.Error(e);
2014 }
2015 return result.Produce();
2016 }
2017
2018 String LSCPServer::AddMidiInstrumentMap(String MapName) {
2019 dmsg(2,("LSCPServer: AddMidiInstrumentMap()\n"));
2020 LSCPResultSet result;
2021 try {
2022 int MapID = MidiInstrumentMapper::AddMap(MapName);
2023 result = LSCPResultSet(MapID);
2024 } catch (Exception e) {
2025 result.Error(e);
2026 }
2027 return result.Produce();
2028 }
2029
2030 String LSCPServer::RemoveMidiInstrumentMap(uint MidiMapID) {
2031 dmsg(2,("LSCPServer: RemoveMidiInstrumentMap()\n"));
2032 LSCPResultSet result;
2033 try {
2034 MidiInstrumentMapper::RemoveMap(MidiMapID);
2035 } catch (Exception e) {
2036 result.Error(e);
2037 }
2038 return result.Produce();
2039 }
2040
2041 String LSCPServer::RemoveAllMidiInstrumentMaps() {
2042 dmsg(2,("LSCPServer: RemoveAllMidiInstrumentMaps()\n"));
2043 LSCPResultSet result;
2044 try {
2045 MidiInstrumentMapper::RemoveAllMaps();
2046 } catch (Exception e) {
2047 result.Error(e);
2048 }
2049 return result.Produce();
2050 }
2051
2052 String LSCPServer::GetMidiInstrumentMaps() {
2053 dmsg(2,("LSCPServer: GetMidiInstrumentMaps()\n"));
2054 LSCPResultSet result;
2055 try {
2056 result.Add(MidiInstrumentMapper::Maps().size());
2057 } catch (Exception e) {
2058 result.Error(e);
2059 }
2060 return result.Produce();
2061 }
2062
2063 String LSCPServer::ListMidiInstrumentMaps() {
2064 dmsg(2,("LSCPServer: ListMidiInstrumentMaps()\n"));
2065 LSCPResultSet result;
2066 try {
2067 std::vector<int> maps = MidiInstrumentMapper::Maps();
2068 String sList;
2069 for (int i = 0; i < maps.size(); i++) {
2070 if (sList != "") sList += ",";
2071 sList += ToString(maps[i]);
2072 }
2073 result.Add(sList);
2074 } catch (Exception e) {
2075 result.Error(e);
2076 }
2077 return result.Produce();
2078 }
2079
2080 String LSCPServer::GetMidiInstrumentMap(uint MidiMapID) {
2081 dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2082 LSCPResultSet result;
2083 try {
2084 result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2085 result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2086 } catch (Exception e) {
2087 result.Error(e);
2088 }
2089 return result.Produce();
2090 }
2091
2092 String LSCPServer::SetMidiInstrumentMapName(uint MidiMapID, String NewName) {
2093 dmsg(2,("LSCPServer: SetMidiInstrumentMapName()\n"));
2094 LSCPResultSet result;
2095 try {
2096 MidiInstrumentMapper::RenameMap(MidiMapID, NewName);
2097 } catch (Exception e) {
2098 result.Error(e);
2099 }
2100 return result.Produce();
2101 }
2102
2103 /**
2104 * Set the MIDI instrument map the given sampler channel shall use for
2105 * handling MIDI program change messages. There are the following two
2106 * special (negative) values:
2107 *
2108 * - (-1) : set to NONE (ignore program changes)
2109 * - (-2) : set to DEFAULT map
2110 */
2111 String LSCPServer::SetChannelMap(uint uiSamplerChannel, int MidiMapID) {
2112 dmsg(2,("LSCPServer: SetChannelMap()\n"));
2113 LSCPResultSet result;
2114 try {
2115 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2116 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2117
2118 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2119 if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
2120
2121 if (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2122 else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
2123 else pEngineChannel->SetMidiInstrumentMap(MidiMapID);
2124 } catch (Exception e) {
2125 result.Error(e);
2126 }
2127 return result.Produce();
2128 }
2129
2130 String LSCPServer::CreateFxSend(uint uiSamplerChannel, uint MidiCtrl, String Name) {
2131 dmsg(2,("LSCPServer: CreateFxSend()\n"));
2132 LSCPResultSet result;
2133 try {
2134 EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2135
2136 FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2137 if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2138
2139 result = LSCPResultSet(pFxSend->Id()); // success
2140 } catch (Exception e) {
2141 result.Error(e);
2142 }
2143 return result.Produce();
2144 }
2145
2146 String LSCPServer::DestroyFxSend(uint uiSamplerChannel, uint FxSendID) {
2147 dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2148 LSCPResultSet result;
2149 try {
2150 EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2151
2152 FxSend* pFxSend = NULL;
2153 for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2154 if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2155 pFxSend = pEngineChannel->GetFxSend(i);
2156 break;
2157 }
2158 }
2159 if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2160 pEngineChannel->RemoveFxSend(pFxSend);
2161 } catch (Exception e) {
2162 result.Error(e);
2163 }
2164 return result.Produce();
2165 }
2166
2167 String LSCPServer::GetFxSends(uint uiSamplerChannel) {
2168 dmsg(2,("LSCPServer: GetFxSends()\n"));
2169 LSCPResultSet result;
2170 try {
2171 EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2172
2173 result.Add(pEngineChannel->GetFxSendCount());
2174 } catch (Exception e) {
2175 result.Error(e);
2176 }
2177 return result.Produce();
2178 }
2179
2180 String LSCPServer::ListFxSends(uint uiSamplerChannel) {
2181 dmsg(2,("LSCPServer: ListFxSends()\n"));
2182 LSCPResultSet result;
2183 String list;
2184 try {
2185 EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2186
2187 for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2188 FxSend* pFxSend = pEngineChannel->GetFxSend(i);
2189 if (list != "") list += ",";
2190 list += ToString(pFxSend->Id());
2191 }
2192 result.Add(list);
2193 } catch (Exception e) {
2194 result.Error(e);
2195 }
2196 return result.Produce();
2197 }
2198
2199 FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2200 EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2201
2202 FxSend* pFxSend = NULL;
2203 for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2204 if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2205 pFxSend = pEngineChannel->GetFxSend(i);
2206 break;
2207 }
2208 }
2209 if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2210 return pFxSend;
2211 }
2212
2213 String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2214 dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2215 LSCPResultSet result;
2216 try {
2217 EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2218 FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2219
2220 // gather audio routing informations
2221 String AudioRouting;
2222 for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
2223 if (AudioRouting != "") AudioRouting += ",";
2224 AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2225 }
2226
2227 // success
2228 result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2229 result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2230 result.Add("LEVEL", ToString(pFxSend->Level()));
2231 result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2232 } catch (Exception e) {
2233 result.Error(e);
2234 }
2235 return result.Produce();
2236 }
2237
2238 String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2239 dmsg(2,("LSCPServer: SetFxSendName()\n"));
2240 LSCPResultSet result;
2241 try {
2242 FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2243
2244 pFxSend->SetName(Name);
2245 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2246 } catch (Exception e) {
2247 result.Error(e);
2248 }
2249 return result.Produce();
2250 }
2251
2252 String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2253 dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2254 LSCPResultSet result;
2255 try {
2256 FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2257
2258 pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2259 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2260 } catch (Exception e) {
2261 result.Error(e);
2262 }
2263 return result.Produce();
2264 }
2265
2266 String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2267 dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2268 LSCPResultSet result;
2269 try {
2270 FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2271
2272 pFxSend->SetMidiController(MidiController);
2273 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2274 } catch (Exception e) {
2275 result.Error(e);
2276 }
2277 return result.Produce();
2278 }
2279
2280 String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2281 dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2282 LSCPResultSet result;
2283 try {
2284 FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2285
2286 pFxSend->SetLevel((float)dLevel);
2287 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2288 } catch (Exception e) {
2289 result.Error(e);
2290 }
2291 return result.Produce();
2292 }
2293
2294 String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2295 dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2296 LSCPResultSet result;
2297 try {
2298 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2299 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2300 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2301 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2302 if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2303 Engine* pEngine = pEngineChannel->GetEngine();
2304 InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2305 if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2306 InstrumentManager::instrument_id_t instrumentID;
2307 instrumentID.FileName = pEngineChannel->InstrumentFileName();
2308 instrumentID.Index = pEngineChannel->InstrumentIndex();
2309 pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2310 } catch (Exception e) {
2311 result.Error(e);
2312 }
2313 return result.Produce();
2314 }
2315
2316 /**
2317 * Will be called by the parser to reset a particular sampler channel.
2318 */
2319 String LSCPServer::ResetChannel(uint uiSamplerChannel) {
2320 dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2321 LSCPResultSet result;
2322 try {
2323 SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2324 if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2325 EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2326 if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2327 pEngineChannel->Reset();
2328 }
2329 catch (Exception e) {
2330 result.Error(e);
2331 }
2332 return result.Produce();
2333 }
2334
2335 /**
2336 * Will be called by the parser to reset the whole sampler.
2337 */
2338 String LSCPServer::ResetSampler() {
2339 dmsg(2,("LSCPServer: ResetSampler()\n"));
2340 pSampler->Reset();
2341 LSCPResultSet result;
2342 return result.Produce();
2343 }
2344
2345 /**
2346 * Will be called by the parser to return general informations about this
2347 * sampler.
2348 */
2349 String LSCPServer::GetServerInfo() {
2350 dmsg(2,("LSCPServer: GetServerInfo()\n"));
2351 const std::string description =
2352 _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2353 LSCPResultSet result;
2354 result.Add("DESCRIPTION", description);
2355 result.Add("VERSION", VERSION);
2356 result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2357 #if HAVE_SQLITE3
2358 result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2359 #else
2360 result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2361 #endif
2362
2363 return result.Produce();
2364 }
2365
2366 /**
2367 * Will be called by the parser to return the current number of all active streams.
2368 */
2369 String LSCPServer::GetTotalStreamCount() {
2370 dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2371 LSCPResultSet result;
2372 result.Add(pSampler->GetDiskStreamCount());
2373 return result.Produce();
2374 }
2375
2376 /**
2377 * Will be called by the parser to return the current number of all active voices.
2378 */
2379 String LSCPServer::GetTotalVoiceCount() {
2380 dmsg(2,("LSCPServer: GetTotalVoiceCount()\n"));
2381 LSCPResultSet result;
2382 result.Add(pSampler->GetVoiceCount());
2383 return result.Produce();
2384 }
2385
2386 /**
2387 * Will be called by the parser to return the maximum number of voices.
2388 */
2389 String LSCPServer::GetTotalVoiceCountMax() {
2390 dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2391 LSCPResultSet result;
2392 result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);
2393 return result.Produce();
2394 }
2395
2396 String LSCPServer::GetGlobalVolume() {
2397 LSCPResultSet result;
2398 result.Add(ToString(GLOBAL_VOLUME)); // see common/global.cpp
2399 return result.Produce();
2400 }
2401
2402 String LSCPServer::SetGlobalVolume(double dVolume) {
2403 LSCPResultSet result;
2404 try {
2405 if (dVolume < 0) throw Exception("Volume may not be negative");
2406 GLOBAL_VOLUME = dVolume; // see common/global.cpp
2407 LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2408 } catch (Exception e) {
2409 result.Error(e);
2410 }
2411 return result.Produce();
2412 }
2413
2414 String LSCPServer::GetFileInstruments(String Filename) {
2415 dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2416 LSCPResultSet result;
2417 try {
2418 VerifyFile(Filename);
2419 } catch (Exception e) {
2420 result.Error(e);
2421 return result.Produce();
2422 }
2423 // try to find a sampler engine that can handle the file
2424 bool bFound = false;
2425 std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2426 for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2427 Engine* pEngine = NULL;
2428 try {
2429 pEngine = EngineFactory::Create(engineTypes[i]);
2430 if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2431 InstrumentManager* pManager = pEngine->GetInstrumentManager();
2432 if (pManager) {
2433 std::vector<InstrumentManager::instrument_id_t> IDs =
2434 pManager->GetInstrumentFileContent(Filename);
2435 // return the amount of instruments in the file
2436 result.Add(IDs.size());
2437 // no more need to ask other engine types
2438 bFound = true;
2439 } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2440 } catch (Exception e) {
2441 // NOOP, as exception is thrown if engine doesn't support file
2442 }
2443 if (pEngine) EngineFactory::Destroy(pEngine);
2444 }
2445
2446 if (!bFound) result.Error("Unknown file format");
2447 return result.Produce();
2448 }
2449
2450 String LSCPServer::ListFileInstruments(String Filename) {
2451 dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2452 LSCPResultSet result;
2453 try {
2454 VerifyFile(Filename);
2455 } catch (Exception e) {
2456 result.Error(e);
2457 return result.Produce();
2458 }
2459 // try to find a sampler engine that can handle the file
2460 bool bFound = false;
2461 std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2462 for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2463 Engine* pEngine = NULL;
2464 try {
2465 pEngine = EngineFactory::Create(engineTypes[i]);
2466 if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2467 InstrumentManager* pManager = pEngine->GetInstrumentManager();
2468 if (pManager) {
2469 std::vector<InstrumentManager::instrument_id_t> IDs =
2470 pManager->GetInstrumentFileContent(Filename);
2471 // return a list of IDs of the instruments in the file
2472 String s;
2473 for (int j = 0; j < IDs.size(); j++) {
2474 if (s.size()) s += ",";
2475 s += ToString(IDs[j].Index);
2476 }
2477 result.Add(s);
2478 // no more need to ask other engine types
2479 bFound = true;
2480 } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2481 } catch (Exception e) {
2482 // NOOP, as exception is thrown if engine doesn't support file
2483 }
2484 if (pEngine) EngineFactory::Destroy(pEngine);
2485 }
2486
2487 if (!bFound) result.Error("Unknown file format");
2488 return result.Produce();
2489 }
2490
2491 String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2492 dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2493 LSCPResultSet result;
2494 try {
2495 VerifyFile(Filename);
2496 } catch (Exception e) {
2497 result.Error(e);
2498 return result.Produce();
2499 }
2500 InstrumentManager::instrument_id_t id;
2501 id.FileName = Filename;
2502 id.Index = InstrumentID;
2503 // try to find a sampler engine that can handle the file
2504 bool bFound = false;
2505 bool bFatalErr = false;
2506 std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2507 for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2508 Engine* pEngine = NULL;
2509 try {
2510 pEngine = EngineFactory::Create(engineTypes[i]);
2511 if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2512 InstrumentManager* pManager = pEngine->GetInstrumentManager();
2513 if (pManager) {
2514 // check if the instrument index is valid
2515 // FIXME: this won't work if an engine only supports parts of the instrument file
2516 std::vector<InstrumentManager::instrument_id_t> IDs =
2517 pManager->GetInstrumentFileContent(Filename);
2518 if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2519 std::stringstream ss;
2520 ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2521 bFatalErr = true;
2522 throw Exception(ss.str());
2523 }
2524 // get the info of the requested instrument
2525 InstrumentManager::instrument_info_t info =
2526 pManager->GetInstrumentInfo(id);
2527 // return detailed informations about the file
2528 result.Add("NAME", info.InstrumentName);
2529 result.Add("FORMAT_FAMILY", engineTypes[i]);
2530 result.Add("FORMAT_VERSION", info.FormatVersion);
2531 result.Add("PRODUCT", info.Product);
2532 result.Add("ARTISTS", info.Artists);
2533 // no more need to ask other engine types
2534 bFound = true;
2535 } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2536 } catch (Exception e) {
2537 // usually NOOP, as exception is thrown if engine doesn't support file
2538 if (bFatalErr) result.Error(e);
2539 }
2540 if (pEngine) EngineFactory::Destroy(pEngine);
2541 }
2542
2543 if (!bFound && !bFatalErr) result.Error("Unknown file format");
2544 return result.Produce();
2545 }
2546
2547 void LSCPServer::VerifyFile(String Filename) {
2548 #if WIN32
2549 WIN32_FIND_DATA win32FileAttributeData;
2550 BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2551 if (!res) {
2552 std::stringstream ss;
2553 ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2554 throw Exception(ss.str());
2555 }
2556 if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2557 throw Exception("Directory is specified");
2558 }
2559 #else
2560 struct stat statBuf;
2561 int res = stat(Filename.c_str(), &statBuf);
2562 if (res) {
2563 std::stringstream ss;
2564 ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2565 throw Exception(ss.str());
2566 }
2567
2568 if (S_ISDIR(statBuf.st_mode)) {
2569 throw Exception("Directory is specified");
2570 }
2571 #endif
2572 }
2573
2574 /**
2575 * Will be called by the parser to subscribe a client (frontend) on the
2576 * server for receiving event messages.
2577 */
2578 String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
2579 dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
2580 LSCPResultSet result;
2581 SubscriptionMutex.Lock();
2582 eventSubscriptions[type].push_back(currentSocket);
2583 SubscriptionMutex.Unlock();
2584 return result.Produce();
2585 }
2586
2587 /**
2588 * Will be called by the parser to unsubscribe a client on the server
2589 * for not receiving further event messages.
2590 */
2591 String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
2592 dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
2593 LSCPResultSet result;
2594 SubscriptionMutex.Lock();
2595 eventSubscriptions[type].remove(currentSocket);
2596 SubscriptionMutex.Unlock();
2597 return result.Produce();
2598 }
2599
2600 String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2601 dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2602 LSCPResultSet result;
2603 #if HAVE_SQLITE3
2604 try {
2605 InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2606 } catch (Exception e) {
2607 result.Error(e);
2608 }
2609 #else
2610 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2611 #endif
2612 return result.Produce();
2613 }
2614
2615 String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2616 dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2617 LSCPResultSet result;
2618 #if HAVE_SQLITE3
2619 try {
2620 InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2621 } catch (Exception e) {
2622 result.Error(e);
2623 }
2624 #else
2625 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2626 #endif
2627 return result.Produce();
2628 }
2629
2630 String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2631 dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2632 LSCPResultSet result;
2633 #if HAVE_SQLITE3
2634 try {
2635 result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2636 } catch (Exception e) {
2637 result.Error(e);
2638 }
2639 #else
2640 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2641 #endif
2642 return result.Produce();
2643 }
2644
2645 String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2646 dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2647 LSCPResultSet result;
2648 #if HAVE_SQLITE3
2649 try {
2650 String list;
2651 StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2652
2653 for (int i = 0; i < dirs->size(); i++) {
2654 if (list != "") list += ",";
2655 list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2656 }
2657
2658 result.Add(list);
2659 } catch (Exception e) {
2660 result.Error(e);
2661 }
2662 #else
2663 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2664 #endif
2665 return result.Produce();
2666 }
2667
2668 String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2669 dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2670 LSCPResultSet result;
2671 #if HAVE_SQLITE3
2672 try {
2673 DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2674
2675 result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2676 result.Add("CREATED", info.Created);
2677 result.Add("MODIFIED", info.Modified);
2678 } catch (Exception e) {
2679 result.Error(e);
2680 }
2681 #else
2682 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2683 #endif
2684 return result.Produce();
2685 }
2686
2687 String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2688 dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2689 LSCPResultSet result;
2690 #if HAVE_SQLITE3
2691 try {
2692 InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2693 } catch (Exception e) {
2694 result.Error(e);
2695 }
2696 #else
2697 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2698 #endif
2699 return result.Produce();
2700 }
2701
2702 String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2703 dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2704 LSCPResultSet result;
2705 #if HAVE_SQLITE3
2706 try {
2707 InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2708 } catch (Exception e) {
2709 result.Error(e);
2710 }
2711 #else
2712 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2713 #endif
2714 return result.Produce();
2715 }
2716
2717 String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2718 dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2719 LSCPResultSet result;
2720 #if HAVE_SQLITE3
2721 try {
2722 InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2723 } catch (Exception e) {
2724 result.Error(e);
2725 }
2726 #else
2727 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2728 #endif
2729 return result.Produce();
2730 }
2731
2732 String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2733 dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2734 LSCPResultSet result;
2735 #if HAVE_SQLITE3
2736 try {
2737 InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2738 } catch (Exception e) {
2739 result.Error(e);
2740 }
2741 #else
2742 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2743 #endif
2744 return result.Produce();
2745 }
2746
2747 String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2748 dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2749 LSCPResultSet result;
2750 #if HAVE_SQLITE3
2751 try {
2752 int id;
2753 InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2754 id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2755 if (bBackground) result = id;
2756 } catch (Exception e) {
2757 result.Error(e);
2758 }
2759 #else
2760 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2761 #endif
2762 return result.Produce();
2763 }
2764
2765 String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2766 dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2767 LSCPResultSet result;
2768 #if HAVE_SQLITE3
2769 try {
2770 int id;
2771 InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2772 if (ScanMode.compare("RECURSIVE") == 0) {
2773 id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2774 } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2775 id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2776 } else if (ScanMode.compare("FLAT") == 0) {
2777 id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2778 } else {
2779 throw Exception("Unknown scan mode: " + ScanMode);
2780 }
2781
2782 if (bBackground) result = id;
2783 } catch (Exception e) {
2784 result.Error(e);
2785 }
2786 #else
2787 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2788 #endif
2789 return result.Produce();
2790 }
2791
2792 String LSCPServer::RemoveDbInstrument(String Instr) {
2793 dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2794 LSCPResultSet result;
2795 #if HAVE_SQLITE3
2796 try {
2797 InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2798 } catch (Exception e) {
2799 result.Error(e);
2800 }
2801 #else
2802 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2803 #endif
2804 return result.Produce();
2805 }
2806
2807 String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2808 dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2809 LSCPResultSet result;
2810 #if HAVE_SQLITE3
2811 try {
2812 result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2813 } catch (Exception e) {
2814 result.Error(e);
2815 }
2816 #else
2817 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2818 #endif
2819 return result.Produce();
2820 }
2821
2822 String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2823 dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2824 LSCPResultSet result;
2825 #if HAVE_SQLITE3
2826 try {
2827 String list;
2828 StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2829
2830 for (int i = 0; i < instrs->size(); i++) {
2831 if (list != "") list += ",";
2832 list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2833 }
2834
2835 result.Add(list);
2836 } catch (Exception e) {
2837 result.Error(e);
2838 }
2839 #else
2840 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2841 #endif
2842 return result.Produce();
2843 }
2844
2845 String LSCPServer::GetDbInstrumentInfo(String Instr) {
2846 dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2847 LSCPResultSet result;
2848 #if HAVE_SQLITE3
2849 try {
2850 DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2851
2852 result.Add("INSTRUMENT_FILE", info.InstrFile);
2853 result.Add("INSTRUMENT_NR", info.InstrNr);
2854 result.Add("FORMAT_FAMILY", info.FormatFamily);
2855 result.Add("FORMAT_VERSION", info.FormatVersion);
2856 result.Add("SIZE", (int)info.Size);
2857 result.Add("CREATED", info.Created);
2858 result.Add("MODIFIED", info.Modified);
2859 result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2860 result.Add("IS_DRUM", info.IsDrum);
2861 result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2862 result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2863 result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2864 } catch (Exception e) {
2865 result.Error(e);
2866 }
2867 #else
2868 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2869 #endif
2870 return result.Produce();
2871 }
2872
2873 String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2874 dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2875 LSCPResultSet result;
2876 #if HAVE_SQLITE3
2877 try {
2878 ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
2879
2880 result.Add("FILES_TOTAL", job.FilesTotal);
2881 result.Add("FILES_SCANNED", job.FilesScanned);
2882 result.Add("SCANNING", job.Scanning);
2883 result.Add("STATUS", job.Status);
2884 } catch (Exception e) {
2885 result.Error(e);
2886 }
2887 #else
2888 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2889 #endif
2890 return result.Produce();
2891 }
2892
2893 String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
2894 dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
2895 LSCPResultSet result;
2896 #if HAVE_SQLITE3
2897 try {
2898 InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
2899 } catch (Exception e) {
2900 result.Error(e);
2901 }
2902 #else
2903 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2904 #endif
2905 return result.Produce();
2906 }
2907
2908 String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
2909 dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2910 LSCPResultSet result;
2911 #if HAVE_SQLITE3
2912 try {
2913 InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
2914 } catch (Exception e) {
2915 result.Error(e);
2916 }
2917 #else
2918 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2919 #endif
2920 return result.Produce();
2921 }
2922
2923 String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
2924 dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2925 LSCPResultSet result;
2926 #if HAVE_SQLITE3
2927 try {
2928 InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
2929 } catch (Exception e) {
2930 result.Error(e);
2931 }
2932 #else
2933 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2934 #endif
2935 return result.Produce();
2936 }
2937
2938 String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
2939 dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
2940 LSCPResultSet result;
2941 #if HAVE_SQLITE3
2942 try {
2943 InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
2944 } catch (Exception e) {
2945 result.Error(e);
2946 }
2947 #else
2948 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2949 #endif
2950 return result.Produce();
2951 }
2952
2953 String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
2954 dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
2955 LSCPResultSet result;
2956 #if HAVE_SQLITE3
2957 try {
2958 SearchQuery Query;
2959 std::map<String,String>::iterator iter;
2960 for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2961 if (iter->first.compare("NAME") == 0) {
2962 Query.Name = iter->second;
2963 } else if (iter->first.compare("CREATED") == 0) {
2964 Query.SetCreated(iter->second);
2965 } else if (iter->first.compare("MODIFIED") == 0) {
2966 Query.SetModified(iter->second);
2967 } else if (iter->first.compare("DESCRIPTION") == 0) {
2968 Query.Description = iter->second;
2969 } else {
2970 throw Exception("Unknown search criteria: " + iter->first);
2971 }
2972 }
2973
2974 String list;
2975 StringListPtr pDirectories =
2976 InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
2977
2978 for (int i = 0; i < pDirectories->size(); i++) {
2979 if (list != "") list += ",";
2980 list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
2981 }
2982
2983 result.Add(list);
2984 } catch (Exception e) {
2985 result.Error(e);
2986 }
2987 #else
2988 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2989 #endif
2990 return result.Produce();
2991 }
2992
2993 String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
2994 dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
2995 LSCPResultSet result;
2996 #if HAVE_SQLITE3
2997 try {
2998 SearchQuery Query;
2999 std::map<String,String>::iterator iter;
3000 for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3001 if (iter->first.compare("NAME") == 0) {
3002 Query.Name = iter->second;
3003 } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3004 Query.SetFormatFamilies(iter->second);
3005 } else if (iter->first.compare("SIZE") == 0) {
3006 Query.SetSize(iter->second);
3007 } else if (iter->first.compare("CREATED") == 0) {
3008 Query.SetCreated(iter->second);
3009 } else if (iter->first.compare("MODIFIED") == 0) {
3010 Query.SetModified(iter->second);
3011 } else if (iter->first.compare("DESCRIPTION") == 0) {
3012 Query.Description = iter->second;
3013 } else if (iter->first.compare("IS_DRUM") == 0) {
3014 if (!strcasecmp(iter->second.c_str(), "true")) {
3015 Query.InstrType = SearchQuery::DRUM;
3016 } else {
3017 Query.InstrType = SearchQuery::CHROMATIC;
3018 }
3019 } else if (iter->first.compare("PRODUCT") == 0) {
3020 Query.Product = iter->second;
3021 } else if (iter->first.compare("ARTISTS") == 0) {
3022 Query.Artists = iter->second;
3023 } else if (iter->first.compare("KEYWORDS") == 0) {
3024 Query.Keywords = iter->second;
3025 } else {
3026 throw Exception("Unknown search criteria: " + iter->first);
3027 }
3028 }
3029
3030 String list;
3031 StringListPtr pInstruments =
3032 InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3033
3034 for (int i = 0; i < pInstruments->size(); i++) {
3035 if (list != "") list += ",";
3036 list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3037 }
3038
3039 result.Add(list);
3040 } catch (Exception e) {
3041 result.Error(e);
3042 }
3043 #else
3044 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3045 #endif
3046 return result.Produce();
3047 }
3048
3049 String LSCPServer::FormatInstrumentsDb() {
3050 dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3051 LSCPResultSet result;
3052 #if HAVE_SQLITE3
3053 try {
3054 InstrumentsDb::GetInstrumentsDb()->Format();
3055 } catch (Exception e) {
3056 result.Error(e);
3057 }
3058 #else
3059 result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3060 #endif
3061 return result.Produce();
3062 }
3063
3064
3065 /**
3066 * Will be called by the parser to enable or disable echo mode; if echo
3067 * mode is enabled, all commands from the client will (immediately) be
3068 * echoed back to the client.
3069 */
3070 String LSCPServer::SetEcho(yyparse_param_t* pSession, double boolean_value) {
3071 dmsg(2,("LSCPServer: SetEcho(val=%f)\n", boolean_value));
3072 LSCPResultSet result;
3073 try {
3074 if (boolean_value == 0) pSession->bVerbose = false;
3075 else if (boolean_value == 1) pSession->bVerbose = true;
3076 else throw Exception("Not a boolean value, must either be 0 or 1");
3077 }
3078 catch (Exception e) {
3079 result.Error(e);
3080 }
3081 return result.Produce();
3082 }

  ViewVC Help
Powered by ViewVC