/[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 1765 by persson, Sat Sep 6 16:44:42 2008 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 - 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    
26  #include "lscpserver.h"  #include "lscpserver.h"
27  #include "lscpresultset.h"  #include "lscpresultset.h"
28  #include "lscpevent.h"  #include "lscpevent.h"
29    
30  #if defined(WIN32)  #if defined(WIN32)
31    #include <windows.h>
32  #else  #else
33  #include <fcntl.h>  #include <fcntl.h>
34  #endif  #endif
# Line 39  Line 42 
42  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
43  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
44    
45    namespace LinuxSampler {
46    
47  /**  /**
48   * Returns a copy of the given string where all special characters are   * Returns a copy of the given string where all special characters are
# Line 100  Mutex LSCPServer::NotifyBufferMutex = Mu Line 104  Mutex LSCPServer::NotifyBufferMutex = Mu
104  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
105  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
106    
107  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4) {  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) {
108      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
109      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
110      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 126  LSCPServer::LSCPServer(Sampler* pSampler Line 130  LSCPServer::LSCPServer(Sampler* pSampler
130      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
131      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
132      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
133        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
134      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
135      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
136        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
137        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
138      hSocket = -1;      hSocket = -1;
139  }  }
140    
# Line 139  LSCPServer::~LSCPServer() { Line 146  LSCPServer::~LSCPServer() {
146  #endif  #endif
147  }  }
148    
149    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
150        this->pParent = pParent;
151    }
152    
153    LSCPServer::EventHandler::~EventHandler() {
154        std::vector<midi_listener_entry> l = channelMidiListeners;
155        channelMidiListeners.clear();
156        for (int i = 0; i < l.size(); i++)
157            delete l[i].pMidiListener;
158    }
159    
160  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
161      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
162  }  }
163    
164    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
165        pChannel->AddEngineChangeListener(this);
166    }
167    
168    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
169        if (!pChannel->GetEngineChannel()) return;
170        EngineToBeChanged(pChannel->Index());
171    }
172    
173    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
174        SamplerChannel* pSamplerChannel =
175            pParent->pSampler->GetSamplerChannel(ChannelId);
176        if (!pSamplerChannel) return;
177        EngineChannel* pEngineChannel =
178            pSamplerChannel->GetEngineChannel();
179        if (!pEngineChannel) return;
180        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
181            if ((*iter).pEngineChannel == pEngineChannel) {
182                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
183                pEngineChannel->Disconnect(pMidiListener);
184                channelMidiListeners.erase(iter);
185                delete pMidiListener;
186                return;
187            }
188        }
189    }
190    
191    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
192        SamplerChannel* pSamplerChannel =
193            pParent->pSampler->GetSamplerChannel(ChannelId);
194        if (!pSamplerChannel) return;
195        EngineChannel* pEngineChannel =
196            pSamplerChannel->GetEngineChannel();
197        if (!pEngineChannel) return;
198        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
199        pEngineChannel->Connect(pMidiListener);
200        midi_listener_entry entry = {
201            pSamplerChannel, pEngineChannel, pMidiListener
202        };
203        channelMidiListeners.push_back(entry);
204    }
205    
206  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
207      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
208  }  }
# Line 151  void LSCPServer::EventHandler::MidiDevic Line 211  void LSCPServer::EventHandler::MidiDevic
211      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
212  }  }
213    
214    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
215        pDevice->RemoveMidiPortCountListener(this);
216        for (int i = 0; i < pDevice->PortCount(); ++i)
217            MidiPortToBeRemoved(pDevice->GetPort(i));
218    }
219    
220    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
221        pDevice->AddMidiPortCountListener(this);
222        for (int i = 0; i < pDevice->PortCount(); ++i)
223            MidiPortAdded(pDevice->GetPort(i));
224    }
225    
226    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
227        // yet unused
228    }
229    
230    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
231        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
232            if ((*iter).pPort == pPort) {
233                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
234                pPort->Disconnect(pMidiListener);
235                deviceMidiListeners.erase(iter);
236                delete pMidiListener;
237                return;
238            }
239        }
240    }
241    
242    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
243        // find out the device ID
244        std::map<uint, MidiInputDevice*> devices =
245            pParent->pSampler->GetMidiInputDevices();
246        for (
247            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
248            iter != devices.end(); ++iter
249        ) {
250            if (iter->second == pPort->GetDevice()) { // found
251                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
252                pPort->Connect(pMidiListener);
253                device_midi_listener_entry entry = {
254                    pPort, pMidiListener, iter->first
255                };
256                deviceMidiListeners.push_back(entry);
257                return;
258            }
259        }
260    }
261    
262  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {  void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
263      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
264  }  }
# Line 187  void LSCPServer::EventHandler::TotalVoic Line 295  void LSCPServer::EventHandler::TotalVoic
295      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
296  }  }
297    
298    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
299        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
300    }
301    
302  #if HAVE_SQLITE3  #if HAVE_SQLITE3
303  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
304      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 283  int LSCPServer::Main() { Line 395  int LSCPServer::Main() {
395      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
396      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
397      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
398        pSampler->AddTotalStreamCountListener(&eventHandler);
399      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
400      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
401      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
# Line 302  int LSCPServer::Main() { Line 415  int LSCPServer::Main() {
415      timeval timeout;      timeval timeout;
416    
417      while (true) {      while (true) {
418            #if CONFIG_PTHREAD_TESTCANCEL
419                    TestCancel();
420            #endif
421          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
422          {          {
423              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 309  int LSCPServer::Main() { Line 425  int LSCPServer::Main() {
425              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
426              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
427                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
428                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
429                  }                  }
430    
431                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
432                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
433                      if(fxs != NULL && fxs->IsInfoChanged()) {                      if(fxs != NULL && fxs->IsInfoChanged()) {
434                          int chn = (*itEngineChannel)->iSamplerChannelIndex;                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
435                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
436                          fxs->SetInfoChanged(false);                          fxs->SetInfoChanged(false);
437                      }                      }
# Line 323  int LSCPServer::Main() { Line 439  int LSCPServer::Main() {
439              }              }
440          }          }
441    
442            // check if MIDI data arrived on some engine channel
443            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
444                const EventHandler::midi_listener_entry entry =
445                    eventHandler.channelMidiListeners[i];
446                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
447                if (pMidiListener->NotesChanged()) {
448                    for (int iNote = 0; iNote < 128; iNote++) {
449                        if (pMidiListener->NoteChanged(iNote)) {
450                            const bool bActive = pMidiListener->NoteIsActive(iNote);
451                            LSCPServer::SendLSCPNotify(
452                                LSCPEvent(
453                                    LSCPEvent::event_channel_midi,
454                                    entry.pSamplerChannel->Index(),
455                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
456                                    iNote,
457                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
458                                            : pMidiListener->NoteOffVelocity(iNote)
459                                )
460                            );
461                        }
462                    }
463                }
464            }
465    
466            // check if MIDI data arrived on some MIDI device
467            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
468                const EventHandler::device_midi_listener_entry entry =
469                    eventHandler.deviceMidiListeners[i];
470                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
471                if (pMidiListener->NotesChanged()) {
472                    for (int iNote = 0; iNote < 128; iNote++) {
473                        if (pMidiListener->NoteChanged(iNote)) {
474                            const bool bActive = pMidiListener->NoteIsActive(iNote);
475                            LSCPServer::SendLSCPNotify(
476                                LSCPEvent(
477                                    LSCPEvent::event_device_midi,
478                                    entry.uiDeviceID,
479                                    entry.pPort->GetPortNumber(),
480                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
481                                    iNote,
482                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
483                                            : pMidiListener->NoteOffVelocity(iNote)
484                                )
485                            );
486                        }
487                    }
488                }
489            }
490    
491          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
492          NotifyBufferMutex.Lock();          NotifyBufferMutex.Lock();
493          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 367  int LSCPServer::Main() { Line 532  int LSCPServer::Main() {
532                    std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;                    std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
533                    exit(EXIT_FAILURE);                    exit(EXIT_FAILURE);
534                  }                  }
535          #else                    #else
536                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
537                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
538                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
# Line 439  void LSCPServer::CloseConnection( std::v Line 604  void LSCPServer::CloseConnection( std::v
604          NotifyMutex.Unlock();          NotifyMutex.Unlock();
605  }  }
606    
607    void LSCPServer::LockRTNotify() {
608        RTNotifyMutex.Lock();
609    }
610    
611    void LSCPServer::UnlockRTNotify() {
612        RTNotifyMutex.Unlock();
613    }
614    
615  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
616          int subs = 0;          int subs = 0;
617          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 538  bool LSCPServer::GetLSCPCommand( std::ve Line 711  bool LSCPServer::GetLSCPCommand( std::ve
711                      int wsa_lasterror = WSAGetLastError();                      int wsa_lasterror = WSAGetLastError();
712                          if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.                          if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
713                                  return false;                                  return false;
714                          dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
715                          CloseConnection(iter);                          CloseConnection(iter);
716                          break;                          break;
717                  }                  }
# Line 1848  String LSCPServer::GetMidiInstrumentMapp Line 2021  String LSCPServer::GetMidiInstrumentMapp
2021      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2022      LSCPResultSet result;      LSCPResultSet result;
2023      try {      try {
2024          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2025      } catch (Exception e) {      } catch (Exception e) {
2026          result.Error(e);          result.Error(e);
2027      }      }
# Line 1859  String LSCPServer::GetMidiInstrumentMapp Line 2032  String LSCPServer::GetMidiInstrumentMapp
2032  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2033      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2034      LSCPResultSet result;      LSCPResultSet result;
2035      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2036      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2037      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2038          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2039      }      }
     result.Add(totalMappings);  
2040      return result.Produce();      return result.Produce();
2041  }  }
2042    
# Line 1874  String LSCPServer::GetMidiInstrumentMapp Line 2044  String LSCPServer::GetMidiInstrumentMapp
2044      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2045      LSCPResultSet result;      LSCPResultSet result;
2046      try {      try {
2047          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2048          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2049          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
         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)  
2050  #if WIN32  #if WIN32
2051              const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();          const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2052  #else  #else
2053              // assuming POSIX          // assuming POSIX
2054              const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();          const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2055  #endif  #endif
2056    
2057              result.Add("NAME", _escapeLscpResponse(iter->second.Name));          result.Add("NAME", _escapeLscpResponse(entry.Name));
2058              result.Add("ENGINE_NAME", iter->second.EngineName);          result.Add("ENGINE_NAME", entry.EngineName);
2059              result.Add("INSTRUMENT_FILE", instrumentFileName);          result.Add("INSTRUMENT_FILE", instrumentFileName);
2060              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2061              String instrumentName;          String instrumentName;
2062              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2063              if (pEngine) {          if (pEngine) {
2064                  if (pEngine->GetInstrumentManager()) {              if (pEngine->GetInstrumentManager()) {
2065                      InstrumentManager::instrument_id_t instrID;                  InstrumentManager::instrument_id_t instrID;
2066                      instrID.FileName = iter->second.InstrumentFile;                  instrID.FileName = entry.InstrumentFile;
2067                      instrID.Index    = iter->second.InstrumentIndex;                  instrID.Index    = entry.InstrumentIndex;
2068                      instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                 }  
                 EngineFactory::Destroy(pEngine);  
2069              }              }
2070              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));              EngineFactory::Destroy(pEngine);
2071              switch (iter->second.LoadMode) {          }
2072                  case MidiInstrumentMapper::ON_DEMAND:          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2073                      result.Add("LOAD_MODE", "ON_DEMAND");          switch (entry.LoadMode) {
2074                      break;              case MidiInstrumentMapper::ON_DEMAND:
2075                  case MidiInstrumentMapper::ON_DEMAND_HOLD:                  result.Add("LOAD_MODE", "ON_DEMAND");
2076                      result.Add("LOAD_MODE", "ON_DEMAND_HOLD");                  break;
2077                      break;              case MidiInstrumentMapper::ON_DEMAND_HOLD:
2078                  case MidiInstrumentMapper::PERSISTENT:                  result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2079                      result.Add("LOAD_MODE", "PERSISTENT");                  break;
2080                      break;              case MidiInstrumentMapper::PERSISTENT:
2081                  default:                  result.Add("LOAD_MODE", "PERSISTENT");
2082                      throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");                  break;
2083              }              default:
2084              result.Add("VOLUME", iter->second.Volume);                  throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2085          }          }
2086            result.Add("VOLUME", entry.Volume);
2087      } catch (Exception e) {      } catch (Exception e) {
2088          result.Error(e);          result.Error(e);
2089      }      }
# Line 2346  String LSCPServer::GetServerInfo() { Line 2506  String LSCPServer::GetServerInfo() {
2506  }  }
2507    
2508  /**  /**
2509     * Will be called by the parser to return the current number of all active streams.
2510     */
2511    String LSCPServer::GetTotalStreamCount() {
2512        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2513        LSCPResultSet result;
2514        result.Add(pSampler->GetDiskStreamCount());
2515        return result.Produce();
2516    }
2517    
2518    /**
2519   * 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.
2520   */   */
2521  String LSCPServer::GetTotalVoiceCount() {  String LSCPServer::GetTotalVoiceCount() {
# Line 2375  String LSCPServer::SetGlobalVolume(doubl Line 2545  String LSCPServer::SetGlobalVolume(doubl
2545      LSCPResultSet result;      LSCPResultSet result;
2546      try {      try {
2547          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2548          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2549          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2550      } catch (Exception e) {      } catch (Exception e) {
2551          result.Error(e);          result.Error(e);
# Line 2383  String LSCPServer::SetGlobalVolume(doubl Line 2553  String LSCPServer::SetGlobalVolume(doubl
2553      return result.Produce();      return result.Produce();
2554  }  }
2555    
2556    String LSCPServer::GetFileInstruments(String Filename) {
2557        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2558        LSCPResultSet result;
2559        try {
2560            VerifyFile(Filename);
2561        } catch (Exception e) {
2562            result.Error(e);
2563            return result.Produce();
2564        }
2565        // try to find a sampler engine that can handle the file
2566        bool bFound = false;
2567        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2568        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2569            Engine* pEngine = NULL;
2570            try {
2571                pEngine = EngineFactory::Create(engineTypes[i]);
2572                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2573                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2574                if (pManager) {
2575                    std::vector<InstrumentManager::instrument_id_t> IDs =
2576                        pManager->GetInstrumentFileContent(Filename);
2577                    // return the amount of instruments in the file
2578                    result.Add(IDs.size());
2579                    // no more need to ask other engine types
2580                    bFound = true;
2581                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2582            } catch (Exception e) {
2583                // NOOP, as exception is thrown if engine doesn't support file
2584            }
2585            if (pEngine) EngineFactory::Destroy(pEngine);
2586        }
2587    
2588        if (!bFound) result.Error("Unknown file format");
2589        return result.Produce();
2590    }
2591    
2592    String LSCPServer::ListFileInstruments(String Filename) {
2593        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2594        LSCPResultSet result;
2595        try {
2596            VerifyFile(Filename);
2597        } catch (Exception e) {
2598            result.Error(e);
2599            return result.Produce();
2600        }
2601        // try to find a sampler engine that can handle the file
2602        bool bFound = false;
2603        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2604        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2605            Engine* pEngine = NULL;
2606            try {
2607                pEngine = EngineFactory::Create(engineTypes[i]);
2608                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2609                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2610                if (pManager) {
2611                    std::vector<InstrumentManager::instrument_id_t> IDs =
2612                        pManager->GetInstrumentFileContent(Filename);
2613                    // return a list of IDs of the instruments in the file
2614                    String s;
2615                    for (int j = 0; j < IDs.size(); j++) {
2616                        if (s.size()) s += ",";
2617                        s += ToString(IDs[j].Index);
2618                    }
2619                    result.Add(s);
2620                    // no more need to ask other engine types
2621                    bFound = true;
2622                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2623            } catch (Exception e) {
2624                // NOOP, as exception is thrown if engine doesn't support file
2625            }
2626            if (pEngine) EngineFactory::Destroy(pEngine);
2627        }
2628    
2629        if (!bFound) result.Error("Unknown file format");
2630        return result.Produce();
2631    }
2632    
2633    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2634        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2635        LSCPResultSet result;
2636        try {
2637            VerifyFile(Filename);
2638        } catch (Exception e) {
2639            result.Error(e);
2640            return result.Produce();
2641        }
2642        InstrumentManager::instrument_id_t id;
2643        id.FileName = Filename;
2644        id.Index    = InstrumentID;
2645        // try to find a sampler engine that can handle the file
2646        bool bFound = false;
2647        bool bFatalErr = false;
2648        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2649        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2650            Engine* pEngine = NULL;
2651            try {
2652                pEngine = EngineFactory::Create(engineTypes[i]);
2653                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2654                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2655                if (pManager) {
2656                    // check if the instrument index is valid
2657                    // FIXME: this won't work if an engine only supports parts of the instrument file
2658                    std::vector<InstrumentManager::instrument_id_t> IDs =
2659                        pManager->GetInstrumentFileContent(Filename);
2660                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2661                        std::stringstream ss;
2662                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2663                        bFatalErr = true;
2664                        throw Exception(ss.str());
2665                    }
2666                    // get the info of the requested instrument
2667                    InstrumentManager::instrument_info_t info =
2668                        pManager->GetInstrumentInfo(id);
2669                    // return detailed informations about the file
2670                    result.Add("NAME", info.InstrumentName);
2671                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2672                    result.Add("FORMAT_VERSION", info.FormatVersion);
2673                    result.Add("PRODUCT", info.Product);
2674                    result.Add("ARTISTS", info.Artists);
2675                    // no more need to ask other engine types
2676                    bFound = true;
2677                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2678            } catch (Exception e) {
2679                // usually NOOP, as exception is thrown if engine doesn't support file
2680                if (bFatalErr) result.Error(e);
2681            }
2682            if (pEngine) EngineFactory::Destroy(pEngine);
2683        }
2684    
2685        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2686        return result.Produce();
2687    }
2688    
2689    void LSCPServer::VerifyFile(String Filename) {
2690        #if WIN32
2691        WIN32_FIND_DATA win32FileAttributeData;
2692        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2693        if (!res) {
2694            std::stringstream ss;
2695            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2696            throw Exception(ss.str());
2697        }
2698        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2699            throw Exception("Directory is specified");
2700        }
2701        #else
2702        struct stat statBuf;
2703        int res = stat(Filename.c_str(), &statBuf);
2704        if (res) {
2705            std::stringstream ss;
2706            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2707            throw Exception(ss.str());
2708        }
2709    
2710        if (S_ISDIR(statBuf.st_mode)) {
2711            throw Exception("Directory is specified");
2712        }
2713        #endif
2714    }
2715    
2716  /**  /**
2717   * Will be called by the parser to subscribe a client (frontend) on the   * Will be called by the parser to subscribe a client (frontend) on the
2718   * server for receiving event messages.   * server for receiving event messages.
# Line 2762  String LSCPServer::SetDbInstrumentDescri Line 3092  String LSCPServer::SetDbInstrumentDescri
3092      return result.Produce();      return result.Produce();
3093  }  }
3094    
3095    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3096        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3097        LSCPResultSet result;
3098    #if HAVE_SQLITE3
3099        try {
3100            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3101        } catch (Exception e) {
3102             result.Error(e);
3103        }
3104    #else
3105        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3106    #endif
3107        return result.Produce();
3108    }
3109    
3110    String LSCPServer::FindLostDbInstrumentFiles() {
3111        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3112        LSCPResultSet result;
3113    #if HAVE_SQLITE3
3114        try {
3115            String list;
3116            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3117    
3118            for (int i = 0; i < pLostFiles->size(); i++) {
3119                if (list != "") list += ",";
3120                list += "'" + pLostFiles->at(i) + "'";
3121            }
3122    
3123            result.Add(list);
3124        } catch (Exception e) {
3125             result.Error(e);
3126        }
3127    #else
3128        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3129    #endif
3130        return result.Produce();
3131    }
3132    
3133  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3134      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3135      LSCPResultSet result;      LSCPResultSet result;
# Line 2892  String LSCPServer::SetEcho(yyparse_param Line 3260  String LSCPServer::SetEcho(yyparse_param
3260      }      }
3261      return result.Produce();      return result.Produce();
3262  }  }
3263    
3264    }

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

  ViewVC Help
Powered by ViewVC