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

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

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

revision 1481 by senoner, Wed Nov 14 23:42:15 2007 UTC revision 1835 by iliev, Mon Feb 16 17:56:50 2009 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2008 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    #include <string>
26    
27    #include "../common/File.h"
28  #include "lscpserver.h"  #include "lscpserver.h"
29  #include "lscpresultset.h"  #include "lscpresultset.h"
30  #include "lscpevent.h"  #include "lscpevent.h"
31    
32  #if defined(WIN32)  #if defined(WIN32)
33    #include <windows.h>
34  #else  #else
35  #include <fcntl.h>  #include <fcntl.h>
36  #endif  #endif
# Line 39  Line 44 
44  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
45  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
46    
47    namespace LinuxSampler {
48    
49  /**  /**
50   * Returns a copy of the given string where all special characters are   * Returns a copy of the given string where all special characters are
# Line 100  Mutex LSCPServer::NotifyBufferMutex = Mu Line 106  Mutex LSCPServer::NotifyBufferMutex = Mu
106  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
107  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
108    
109  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4) {  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) {
110      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
111      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
112      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 126  LSCPServer::LSCPServer(Sampler* pSampler Line 132  LSCPServer::LSCPServer(Sampler* pSampler
132      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
133      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
134      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
135        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
136      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
137      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
138        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
139        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
140      hSocket = -1;      hSocket = -1;
141  }  }
142    
# Line 139  LSCPServer::~LSCPServer() { Line 148  LSCPServer::~LSCPServer() {
148  #endif  #endif
149  }  }
150    
151    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
152        this->pParent = pParent;
153    }
154    
155    LSCPServer::EventHandler::~EventHandler() {
156        std::vector<midi_listener_entry> l = channelMidiListeners;
157        channelMidiListeners.clear();
158        for (int i = 0; i < l.size(); i++)
159            delete l[i].pMidiListener;
160    }
161    
162  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
163      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
164  }  }
165    
166    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
167        pChannel->AddEngineChangeListener(this);
168    }
169    
170    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
171        if (!pChannel->GetEngineChannel()) return;
172        EngineToBeChanged(pChannel->Index());
173    }
174    
175    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
176        SamplerChannel* pSamplerChannel =
177            pParent->pSampler->GetSamplerChannel(ChannelId);
178        if (!pSamplerChannel) return;
179        EngineChannel* pEngineChannel =
180            pSamplerChannel->GetEngineChannel();
181        if (!pEngineChannel) return;
182        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
183            if ((*iter).pEngineChannel == pEngineChannel) {
184                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
185                pEngineChannel->Disconnect(pMidiListener);
186                channelMidiListeners.erase(iter);
187                delete pMidiListener;
188                return;
189            }
190        }
191    }
192    
193    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
194        SamplerChannel* pSamplerChannel =
195            pParent->pSampler->GetSamplerChannel(ChannelId);
196        if (!pSamplerChannel) return;
197        EngineChannel* pEngineChannel =
198            pSamplerChannel->GetEngineChannel();
199        if (!pEngineChannel) return;
200        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
201        pEngineChannel->Connect(pMidiListener);
202        midi_listener_entry entry = {
203            pSamplerChannel, pEngineChannel, pMidiListener
204        };
205        channelMidiListeners.push_back(entry);
206    }
207    
208  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
209      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
210  }  }
# Line 151  void LSCPServer::EventHandler::MidiDevic Line 213  void LSCPServer::EventHandler::MidiDevic
213      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
214  }  }
215    
216    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
217        pDevice->RemoveMidiPortCountListener(this);
218        for (int i = 0; i < pDevice->PortCount(); ++i)
219            MidiPortToBeRemoved(pDevice->GetPort(i));
220    }
221    
222    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
223        pDevice->AddMidiPortCountListener(this);
224        for (int i = 0; i < pDevice->PortCount(); ++i)
225            MidiPortAdded(pDevice->GetPort(i));
226    }
227    
228    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
229        // yet unused
230    }
231    
232    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
233        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
234            if ((*iter).pPort == pPort) {
235                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
236                pPort->Disconnect(pMidiListener);
237                deviceMidiListeners.erase(iter);
238                delete pMidiListener;
239                return;
240            }
241        }
242    }
243    
244    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
245        // find out the device ID
246        std::map<uint, MidiInputDevice*> devices =
247            pParent->pSampler->GetMidiInputDevices();
248        for (
249            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
250            iter != devices.end(); ++iter
251        ) {
252            if (iter->second == pPort->GetDevice()) { // found
253                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
254                pPort->Connect(pMidiListener);
255                device_midi_listener_entry entry = {
256                    pPort, pMidiListener, iter->first
257                };
258                deviceMidiListeners.push_back(entry);
259                return;
260            }
261        }
262    }
263    
264  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
265      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
266  }  }
# Line 187  void LSCPServer::EventHandler::TotalVoic Line 297  void LSCPServer::EventHandler::TotalVoic
297      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
298  }  }
299    
300    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
301        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
302    }
303    
304  #if HAVE_SQLITE3  #if HAVE_SQLITE3
305  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
306      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
# Line 221  void LSCPServer::DbInstrumentsEventHandl Line 335  void LSCPServer::DbInstrumentsEventHandl
335  }  }
336  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
337    
338    void LSCPServer::RemoveListeners() {
339        pSampler->RemoveChannelCountListener(&eventHandler);
340        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
341        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
342        pSampler->RemoveVoiceCountListener(&eventHandler);
343        pSampler->RemoveStreamCountListener(&eventHandler);
344        pSampler->RemoveBufferFillListener(&eventHandler);
345        pSampler->RemoveTotalStreamCountListener(&eventHandler);
346        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
347        pSampler->RemoveFxSendCountListener(&eventHandler);
348        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
349        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
350        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
351        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
352    #if HAVE_SQLITE3
353        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
354    #endif
355    }
356    
357  /**  /**
358   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 283  int LSCPServer::Main() { Line 415  int LSCPServer::Main() {
415      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
416      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
417      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
418        pSampler->AddTotalStreamCountListener(&eventHandler);
419      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
420      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
421      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
# Line 302  int LSCPServer::Main() { Line 435  int LSCPServer::Main() {
435      timeval timeout;      timeval timeout;
436    
437      while (true) {      while (true) {
438            #if CONFIG_PTHREAD_TESTCANCEL
439                    TestCancel();
440            #endif
441          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
442          {          {
443              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 309  int LSCPServer::Main() { Line 445  int LSCPServer::Main() {
445              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
446              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
447                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
448                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
449                  }                  }
450    
451                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
452                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
453                      if(fxs != NULL && fxs->IsInfoChanged()) {                      if(fxs != NULL && fxs->IsInfoChanged()) {
454                          int chn = (*itEngineChannel)->iSamplerChannelIndex;                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
455                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
456                          fxs->SetInfoChanged(false);                          fxs->SetInfoChanged(false);
457                      }                      }
# Line 323  int LSCPServer::Main() { Line 459  int LSCPServer::Main() {
459              }              }
460          }          }
461    
462            // check if MIDI data arrived on some engine channel
463            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
464                const EventHandler::midi_listener_entry entry =
465                    eventHandler.channelMidiListeners[i];
466                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
467                if (pMidiListener->NotesChanged()) {
468                    for (int iNote = 0; iNote < 128; iNote++) {
469                        if (pMidiListener->NoteChanged(iNote)) {
470                            const bool bActive = pMidiListener->NoteIsActive(iNote);
471                            LSCPServer::SendLSCPNotify(
472                                LSCPEvent(
473                                    LSCPEvent::event_channel_midi,
474                                    entry.pSamplerChannel->Index(),
475                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
476                                    iNote,
477                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
478                                            : pMidiListener->NoteOffVelocity(iNote)
479                                )
480                            );
481                        }
482                    }
483                }
484            }
485    
486            // check if MIDI data arrived on some MIDI device
487            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
488                const EventHandler::device_midi_listener_entry entry =
489                    eventHandler.deviceMidiListeners[i];
490                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
491                if (pMidiListener->NotesChanged()) {
492                    for (int iNote = 0; iNote < 128; iNote++) {
493                        if (pMidiListener->NoteChanged(iNote)) {
494                            const bool bActive = pMidiListener->NoteIsActive(iNote);
495                            LSCPServer::SendLSCPNotify(
496                                LSCPEvent(
497                                    LSCPEvent::event_device_midi,
498                                    entry.uiDeviceID,
499                                    entry.pPort->GetPortNumber(),
500                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
501                                    iNote,
502                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
503                                            : pMidiListener->NoteOffVelocity(iNote)
504                                )
505                            );
506                        }
507                    }
508                }
509            }
510    
511          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
512          NotifyBufferMutex.Lock();          NotifyBufferMutex.Lock();
513          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
# Line 341  int LSCPServer::Main() { Line 526  int LSCPServer::Main() {
526    
527          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
528    
529          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
530                  continue; //Nothing try again                  continue; //Nothing try again
531          if (retval == -1) {          if (retval == -1) {
532                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
# Line 367  int LSCPServer::Main() { Line 552  int LSCPServer::Main() {
552                    std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;                    std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
553                    exit(EXIT_FAILURE);                    exit(EXIT_FAILURE);
554                  }                  }
555          #else                    #else
556                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
557                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
558                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
# Line 439  void LSCPServer::CloseConnection( std::v Line 624  void LSCPServer::CloseConnection( std::v
624          NotifyMutex.Unlock();          NotifyMutex.Unlock();
625  }  }
626    
627    void LSCPServer::LockRTNotify() {
628        RTNotifyMutex.Lock();
629    }
630    
631    void LSCPServer::UnlockRTNotify() {
632        RTNotifyMutex.Unlock();
633    }
634    
635  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
636          int subs = 0;          int subs = 0;
637          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 538  bool LSCPServer::GetLSCPCommand( std::ve Line 731  bool LSCPServer::GetLSCPCommand( std::ve
731                      int wsa_lasterror = WSAGetLastError();                      int wsa_lasterror = WSAGetLastError();
732                          if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.                          if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
733                                  return false;                                  return false;
734                          dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
735                          CloseConnection(iter);                          CloseConnection(iter);
736                          break;                          break;
737                  }                  }
# Line 961  String LSCPServer::GetVoiceCount(uint ui Line 1154  String LSCPServer::GetVoiceCount(uint ui
1154      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1155      LSCPResultSet result;      LSCPResultSet result;
1156      try {      try {
1157          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine loaded on sampler channel");  
1158          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1159          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1160      }      }
# Line 982  String LSCPServer::GetStreamCount(uint u Line 1172  String LSCPServer::GetStreamCount(uint u
1172      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1173      LSCPResultSet result;      LSCPResultSet result;
1174      try {      try {
1175          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1176          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1177          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1178      }      }
# Line 1003  String LSCPServer::GetBufferFill(fill_re Line 1190  String LSCPServer::GetBufferFill(fill_re
1190      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1191      LSCPResultSet result;      LSCPResultSet result;
1192      try {      try {
1193          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1194          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1195          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1196          else {          else {
# Line 1094  String LSCPServer::GetMidiInputDriverInf Line 1278  String LSCPServer::GetMidiInputDriverInf
1278              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1279                  if (s != "") s += ",";                  if (s != "") s += ",";
1280                  s += iter->first;                  s += iter->first;
1281                    delete iter->second;
1282              }              }
1283              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1284          }          }
# Line 1118  String LSCPServer::GetAudioOutputDriverI Line 1303  String LSCPServer::GetAudioOutputDriverI
1303              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1304                  if (s != "") s += ",";                  if (s != "") s += ",";
1305                  s += iter->first;                  s += iter->first;
1306                    delete iter->second;
1307              }              }
1308              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1309          }          }
# Line 1148  String LSCPServer::GetMidiInputDriverPar Line 1334  String LSCPServer::GetMidiInputDriverPar
1334          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1335          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1336          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1337            delete pParameter;
1338      }      }
1339      catch (Exception e) {      catch (Exception e) {
1340          result.Error(e);          result.Error(e);
# Line 1175  String LSCPServer::GetAudioOutputDriverP Line 1362  String LSCPServer::GetAudioOutputDriverP
1362          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1363          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1364          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1365            delete pParameter;
1366      }      }
1367      catch (Exception e) {      catch (Exception e) {
1368          result.Error(e);          result.Error(e);
# Line 1684  String LSCPServer::SetVolume(double dVol Line 1872  String LSCPServer::SetVolume(double dVol
1872      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1873      LSCPResultSet result;      LSCPResultSet result;
1874      try {      try {
1875          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1876          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
1877      }      }
1878      catch (Exception e) {      catch (Exception e) {
# Line 1703  String LSCPServer::SetChannelMute(bool b Line 1888  String LSCPServer::SetChannelMute(bool b
1888      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1889      LSCPResultSet result;      LSCPResultSet result;
1890      try {      try {
1891          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1892    
1893          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1894          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1724  String LSCPServer::SetChannelSolo(bool b Line 1905  String LSCPServer::SetChannelSolo(bool b
1905      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1906      LSCPResultSet result;      LSCPResultSet result;
1907      try {      try {
1908          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1909    
1910          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1911          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
# Line 1848  String LSCPServer::GetMidiInstrumentMapp Line 2025  String LSCPServer::GetMidiInstrumentMapp
2025      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2026      LSCPResultSet result;      LSCPResultSet result;
2027      try {      try {
2028          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2029      } catch (Exception e) {      } catch (Exception e) {
2030          result.Error(e);          result.Error(e);
2031      }      }
# Line 1859  String LSCPServer::GetMidiInstrumentMapp Line 2036  String LSCPServer::GetMidiInstrumentMapp
2036  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2037      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2038      LSCPResultSet result;      LSCPResultSet result;
2039      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2040      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2041      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2042          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2043      }      }
     result.Add(totalMappings);  
2044      return result.Produce();      return result.Produce();
2045  }  }
2046    
# Line 1874  String LSCPServer::GetMidiInstrumentMapp Line 2048  String LSCPServer::GetMidiInstrumentMapp
2048      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2049      LSCPResultSet result;      LSCPResultSet result;
2050      try {      try {
2051          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2052          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2053          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
         idx.midi_prog     = MidiProg;  
   
         std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);  
         std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);  
         if (iter == mappings.end()) result.Error("there is no map entry with that index");  
         else { // found  
   
             // convert the filename into the correct encoding as defined for LSCP  
             // (especially in terms of special characters -> escape sequences)  
2054  #if WIN32  #if WIN32
2055              const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();          const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2056  #else  #else
2057              // assuming POSIX          // assuming POSIX
2058              const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();          const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2059  #endif  #endif
2060    
2061              result.Add("NAME", _escapeLscpResponse(iter->second.Name));          result.Add("NAME", _escapeLscpResponse(entry.Name));
2062              result.Add("ENGINE_NAME", iter->second.EngineName);          result.Add("ENGINE_NAME", entry.EngineName);
2063              result.Add("INSTRUMENT_FILE", instrumentFileName);          result.Add("INSTRUMENT_FILE", instrumentFileName);
2064              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2065              String instrumentName;          String instrumentName;
2066              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2067              if (pEngine) {          if (pEngine) {
2068                  if (pEngine->GetInstrumentManager()) {              if (pEngine->GetInstrumentManager()) {
2069                      InstrumentManager::instrument_id_t instrID;                  InstrumentManager::instrument_id_t instrID;
2070                      instrID.FileName = iter->second.InstrumentFile;                  instrID.FileName = entry.InstrumentFile;
2071                      instrID.Index    = iter->second.InstrumentIndex;                  instrID.Index    = entry.InstrumentIndex;
2072                      instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                 }  
                 EngineFactory::Destroy(pEngine);  
2073              }              }
2074              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));              EngineFactory::Destroy(pEngine);
2075              switch (iter->second.LoadMode) {          }
2076                  case MidiInstrumentMapper::ON_DEMAND:          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2077                      result.Add("LOAD_MODE", "ON_DEMAND");          switch (entry.LoadMode) {
2078                      break;              case MidiInstrumentMapper::ON_DEMAND:
2079                  case MidiInstrumentMapper::ON_DEMAND_HOLD:                  result.Add("LOAD_MODE", "ON_DEMAND");
2080                      result.Add("LOAD_MODE", "ON_DEMAND_HOLD");                  break;
2081                      break;              case MidiInstrumentMapper::ON_DEMAND_HOLD:
2082                  case MidiInstrumentMapper::PERSISTENT:                  result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2083                      result.Add("LOAD_MODE", "PERSISTENT");                  break;
2084                      break;              case MidiInstrumentMapper::PERSISTENT:
2085                  default:                  result.Add("LOAD_MODE", "PERSISTENT");
2086                      throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");                  break;
2087              }              default:
2088              result.Add("VOLUME", iter->second.Volume);                  throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2089          }          }
2090            result.Add("VOLUME", entry.Volume);
2091      } catch (Exception e) {      } catch (Exception e) {
2092          result.Error(e);          result.Error(e);
2093      }      }
# Line 2094  String LSCPServer::SetChannelMap(uint ui Line 2258  String LSCPServer::SetChannelMap(uint ui
2258      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2259      LSCPResultSet result;      LSCPResultSet result;
2260      try {      try {
2261          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2262    
2263          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2264          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 2277  String LSCPServer::EditSamplerChannelIns Line 2437  String LSCPServer::EditSamplerChannelIns
2437      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2438      LSCPResultSet result;      LSCPResultSet result;
2439      try {      try {
2440          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2441          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2442          Engine* pEngine = pEngineChannel->GetEngine();          Engine* pEngine = pEngineChannel->GetEngine();
2443          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
# Line 2295  String LSCPServer::EditSamplerChannelIns Line 2452  String LSCPServer::EditSamplerChannelIns
2452      return result.Produce();      return result.Produce();
2453  }  }
2454    
2455    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2456        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2457        LSCPResultSet result;
2458        try {
2459            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2460    
2461            if (Arg1 > 127 || Arg2 > 127) {
2462                throw Exception("Invalid MIDI message");
2463            }
2464    
2465            VirtualMidiDevice* pMidiDevice = NULL;
2466            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2467            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2468                if ((*iter).pEngineChannel == pEngineChannel) {
2469                    pMidiDevice = (*iter).pMidiListener;
2470                    break;
2471                }
2472            }
2473            
2474            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2475    
2476            if (MidiMsg == "NOTE_ON") {
2477                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2478                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2479                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2480            } else if (MidiMsg == "NOTE_OFF") {
2481                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2482                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2483                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2484            } else {
2485                throw Exception("Unknown MIDI message type: " + MidiMsg);
2486            }
2487        } catch (Exception e) {
2488            result.Error(e);
2489        }
2490        return result.Produce();
2491    }
2492    
2493  /**  /**
2494   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2495   */   */
# Line 2302  String LSCPServer::ResetChannel(uint uiS Line 2497  String LSCPServer::ResetChannel(uint uiS
2497      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2498      LSCPResultSet result;      LSCPResultSet result;
2499      try {      try {
2500          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2501          pEngineChannel->Reset();          pEngineChannel->Reset();
2502      }      }
2503      catch (Exception e) {      catch (Exception e) {
# Line 2346  String LSCPServer::GetServerInfo() { Line 2538  String LSCPServer::GetServerInfo() {
2538  }  }
2539    
2540  /**  /**
2541     * Will be called by the parser to return the current number of all active streams.
2542     */
2543    String LSCPServer::GetTotalStreamCount() {
2544        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2545        LSCPResultSet result;
2546        result.Add(pSampler->GetDiskStreamCount());
2547        return result.Produce();
2548    }
2549    
2550    /**
2551   * Will be called by the parser to return the current number of all active voices.   * Will be called by the parser to return the current number of all active voices.
2552   */   */
2553  String LSCPServer::GetTotalVoiceCount() {  String LSCPServer::GetTotalVoiceCount() {
# Line 2361  String LSCPServer::GetTotalVoiceCount() Line 2563  String LSCPServer::GetTotalVoiceCount()
2563  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
2564      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2565      LSCPResultSet result;      LSCPResultSet result;
2566      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
2567        return result.Produce();
2568    }
2569    
2570    /**
2571     * Will be called by the parser to return the sampler global maximum
2572     * allowed number of voices.
2573     */
2574    String LSCPServer::GetGlobalMaxVoices() {
2575        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
2576        LSCPResultSet result;
2577        result.Add(GLOBAL_MAX_VOICES);
2578        return result.Produce();
2579    }
2580    
2581    /**
2582     * Will be called by the parser to set the sampler global maximum number of
2583     * voices.
2584     */
2585    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
2586        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
2587        LSCPResultSet result;
2588        try {
2589            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
2590            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
2591            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2592            if (engines.size() > 0) {
2593                std::set<Engine*>::iterator iter = engines.begin();
2594                std::set<Engine*>::iterator end  = engines.end();
2595                for (; iter != end; ++iter) {
2596                    (*iter)->SetMaxVoices(iVoices);
2597                }
2598            }
2599            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
2600        } catch (Exception e) {
2601            result.Error(e);
2602        }
2603        return result.Produce();
2604    }
2605    
2606    /**
2607     * Will be called by the parser to return the sampler global maximum
2608     * allowed number of disk streams.
2609     */
2610    String LSCPServer::GetGlobalMaxStreams() {
2611        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
2612        LSCPResultSet result;
2613        result.Add(GLOBAL_MAX_STREAMS);
2614        return result.Produce();
2615    }
2616    
2617    /**
2618     * Will be called by the parser to set the sampler global maximum number of
2619     * disk streams.
2620     */
2621    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
2622        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
2623        LSCPResultSet result;
2624        try {
2625            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
2626            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
2627            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2628            if (engines.size() > 0) {
2629                std::set<Engine*>::iterator iter = engines.begin();
2630                std::set<Engine*>::iterator end  = engines.end();
2631                for (; iter != end; ++iter) {
2632                    (*iter)->SetMaxDiskStreams(iStreams);
2633                }
2634            }
2635            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
2636        } catch (Exception e) {
2637            result.Error(e);
2638        }
2639      return result.Produce();      return result.Produce();
2640  }  }
2641    
# Line 2375  String LSCPServer::SetGlobalVolume(doubl Line 2649  String LSCPServer::SetGlobalVolume(doubl
2649      LSCPResultSet result;      LSCPResultSet result;
2650      try {      try {
2651          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2652          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2653          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2654      } catch (Exception e) {      } catch (Exception e) {
2655          result.Error(e);          result.Error(e);
# Line 2383  String LSCPServer::SetGlobalVolume(doubl Line 2657  String LSCPServer::SetGlobalVolume(doubl
2657      return result.Produce();      return result.Produce();
2658  }  }
2659    
2660    String LSCPServer::GetFileInstruments(String Filename) {
2661        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2662        LSCPResultSet result;
2663        try {
2664            VerifyFile(Filename);
2665        } catch (Exception e) {
2666            result.Error(e);
2667            return result.Produce();
2668        }
2669        // try to find a sampler engine that can handle the file
2670        bool bFound = false;
2671        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2672        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2673            Engine* pEngine = NULL;
2674            try {
2675                pEngine = EngineFactory::Create(engineTypes[i]);
2676                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2677                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2678                if (pManager) {
2679                    std::vector<InstrumentManager::instrument_id_t> IDs =
2680                        pManager->GetInstrumentFileContent(Filename);
2681                    // return the amount of instruments in the file
2682                    result.Add(IDs.size());
2683                    // no more need to ask other engine types
2684                    bFound = true;
2685                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2686            } catch (Exception e) {
2687                // NOOP, as exception is thrown if engine doesn't support file
2688            }
2689            if (pEngine) EngineFactory::Destroy(pEngine);
2690        }
2691    
2692        if (!bFound) result.Error("Unknown file format");
2693        return result.Produce();
2694    }
2695    
2696    String LSCPServer::ListFileInstruments(String Filename) {
2697        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2698        LSCPResultSet result;
2699        try {
2700            VerifyFile(Filename);
2701        } catch (Exception e) {
2702            result.Error(e);
2703            return result.Produce();
2704        }
2705        // try to find a sampler engine that can handle the file
2706        bool bFound = false;
2707        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2708        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2709            Engine* pEngine = NULL;
2710            try {
2711                pEngine = EngineFactory::Create(engineTypes[i]);
2712                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2713                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2714                if (pManager) {
2715                    std::vector<InstrumentManager::instrument_id_t> IDs =
2716                        pManager->GetInstrumentFileContent(Filename);
2717                    // return a list of IDs of the instruments in the file
2718                    String s;
2719                    for (int j = 0; j < IDs.size(); j++) {
2720                        if (s.size()) s += ",";
2721                        s += ToString(IDs[j].Index);
2722                    }
2723                    result.Add(s);
2724                    // no more need to ask other engine types
2725                    bFound = true;
2726                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2727            } catch (Exception e) {
2728                // NOOP, as exception is thrown if engine doesn't support file
2729            }
2730            if (pEngine) EngineFactory::Destroy(pEngine);
2731        }
2732    
2733        if (!bFound) result.Error("Unknown file format");
2734        return result.Produce();
2735    }
2736    
2737    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2738        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2739        LSCPResultSet result;
2740        try {
2741            VerifyFile(Filename);
2742        } catch (Exception e) {
2743            result.Error(e);
2744            return result.Produce();
2745        }
2746        InstrumentManager::instrument_id_t id;
2747        id.FileName = Filename;
2748        id.Index    = InstrumentID;
2749        // try to find a sampler engine that can handle the file
2750        bool bFound = false;
2751        bool bFatalErr = false;
2752        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2753        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2754            Engine* pEngine = NULL;
2755            try {
2756                pEngine = EngineFactory::Create(engineTypes[i]);
2757                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2758                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2759                if (pManager) {
2760                    // check if the instrument index is valid
2761                    // FIXME: this won't work if an engine only supports parts of the instrument file
2762                    std::vector<InstrumentManager::instrument_id_t> IDs =
2763                        pManager->GetInstrumentFileContent(Filename);
2764                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2765                        std::stringstream ss;
2766                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2767                        bFatalErr = true;
2768                        throw Exception(ss.str());
2769                    }
2770                    // get the info of the requested instrument
2771                    InstrumentManager::instrument_info_t info =
2772                        pManager->GetInstrumentInfo(id);
2773                    // return detailed informations about the file
2774                    result.Add("NAME", info.InstrumentName);
2775                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2776                    result.Add("FORMAT_VERSION", info.FormatVersion);
2777                    result.Add("PRODUCT", info.Product);
2778                    result.Add("ARTISTS", info.Artists);
2779    
2780                    std::stringstream ss;
2781                    bool b = false;
2782                    for (int i = 0; i < 128; i++) {
2783                        if (info.KeyBindings[i]) {
2784                            if (b) ss << ',';
2785                            ss << i; b = true;
2786                        }
2787                    }
2788                    result.Add("KEY_BINDINGS", ss.str());
2789    
2790                    b = false;
2791                    std::stringstream ss2;
2792                    for (int i = 0; i < 128; i++) {
2793                        if (info.KeySwitchBindings[i]) {
2794                            if (b) ss2 << ',';
2795                            ss2 << i; b = true;
2796                        }
2797                    }
2798                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
2799                    // no more need to ask other engine types
2800                    bFound = true;
2801                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2802            } catch (Exception e) {
2803                // usually NOOP, as exception is thrown if engine doesn't support file
2804                if (bFatalErr) result.Error(e);
2805            }
2806            if (pEngine) EngineFactory::Destroy(pEngine);
2807        }
2808    
2809        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2810        return result.Produce();
2811    }
2812    
2813    void LSCPServer::VerifyFile(String Filename) {
2814        #if WIN32
2815        WIN32_FIND_DATA win32FileAttributeData;
2816        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2817        if (!res) {
2818            std::stringstream ss;
2819            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2820            throw Exception(ss.str());
2821        }
2822        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2823            throw Exception("Directory is specified");
2824        }
2825        #else
2826        File f(Filename);
2827        if(!f.Exist()) throw Exception(f.GetErrorMsg());
2828        if (f.IsDirectory()) throw Exception("Directory is specified");
2829        #endif
2830    }
2831    
2832  /**  /**
2833   * Will be called by the parser to subscribe a client (frontend) on the   * Will be called by the parser to subscribe a client (frontend) on the
2834   * server for receiving event messages.   * server for receiving event messages.
# Line 2574  String LSCPServer::AddDbInstruments(Stri Line 3020  String LSCPServer::AddDbInstruments(Stri
3020      return result.Produce();      return result.Produce();
3021  }  }
3022    
3023  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3024      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
3025      LSCPResultSet result;      LSCPResultSet result;
3026  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3027      try {      try {
3028          int id;          int id;
3029          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3030          if (ScanMode.compare("RECURSIVE") == 0) {          if (ScanMode.compare("RECURSIVE") == 0) {
3031             id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3032          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3033             id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3034          } else if (ScanMode.compare("FLAT") == 0) {          } else if (ScanMode.compare("FLAT") == 0) {
3035             id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);              id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3036          } else {          } else {
3037              throw Exception("Unknown scan mode: " + ScanMode);              throw Exception("Unknown scan mode: " + ScanMode);
3038          }          }
# Line 2762  String LSCPServer::SetDbInstrumentDescri Line 3208  String LSCPServer::SetDbInstrumentDescri
3208      return result.Produce();      return result.Produce();
3209  }  }
3210    
3211    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3212        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3213        LSCPResultSet result;
3214    #if HAVE_SQLITE3
3215        try {
3216            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3217        } catch (Exception e) {
3218             result.Error(e);
3219        }
3220    #else
3221        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3222    #endif
3223        return result.Produce();
3224    }
3225    
3226    String LSCPServer::FindLostDbInstrumentFiles() {
3227        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3228        LSCPResultSet result;
3229    #if HAVE_SQLITE3
3230        try {
3231            String list;
3232            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3233    
3234            for (int i = 0; i < pLostFiles->size(); i++) {
3235                if (list != "") list += ",";
3236                list += "'" + pLostFiles->at(i) + "'";
3237            }
3238    
3239            result.Add(list);
3240        } catch (Exception e) {
3241             result.Error(e);
3242        }
3243    #else
3244        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3245    #endif
3246        return result.Produce();
3247    }
3248    
3249  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3250      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3251      LSCPResultSet result;      LSCPResultSet result;
# Line 2892  String LSCPServer::SetEcho(yyparse_param Line 3376  String LSCPServer::SetEcho(yyparse_param
3376      }      }
3377      return result.Produce();      return result.Produce();
3378  }  }
3379    
3380    }

Legend:
Removed from v.1481  
changed lines
  Added in v.1835

  ViewVC Help
Powered by ViewVC