--- linuxsampler/trunk/src/network/lscpserver.cpp 2007/09/16 23:06:10 1350 +++ linuxsampler/trunk/src/network/lscpserver.cpp 2008/09/10 15:02:24 1771 @@ -3,7 +3,7 @@ * LinuxSampler - modular, streaming capable sampler * * * * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck * - * Copyright (C) 2005 - 2007 Christian Schoenebeck * + * Copyright (C) 2005 - 2008 Christian Schoenebeck * * * * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * @@ -21,11 +21,18 @@ * MA 02111-1307 USA * ***************************************************************************/ +#include +#include + #include "lscpserver.h" #include "lscpresultset.h" #include "lscpevent.h" +#if defined(WIN32) +#include +#else #include +#endif #if ! HAVE_SQLITE3 #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built." @@ -36,6 +43,43 @@ #include "../drivers/audio/AudioOutputDeviceFactory.h" #include "../drivers/midi/MidiInputDeviceFactory.h" +namespace LinuxSampler { + +/** + * Returns a copy of the given string where all special characters are + * replaced by LSCP escape sequences ("\xHH"). This function shall be used + * to escape LSCP response fields in case the respective response field is + * actually defined as using escape sequences in the LSCP specs. + * + * @e Caution: DO NOT use this function for escaping path based responses, + * use the Path class (src/common/Path.h) for this instead! + */ +static String _escapeLscpResponse(String txt) { + for (int i = 0; i < txt.length(); i++) { + const char c = txt.c_str()[i]; + if ( + !(c >= '0' && c <= '9') && + !(c >= 'a' && c <= 'z') && + !(c >= 'A' && c <= 'Z') && + !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') && + !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') && + !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') && + !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') && + !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') && + !(c == '@') && !(c == '[') && !(c == ']') && + !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') && + !(c == '|') && !(c == '}') && !(c == '~') + ) { + // convert the "special" character into a "\xHH" LSCP escape sequence + char buf[5]; + snprintf(buf, sizeof(buf), "\\x%02x", static_cast(c)); + txt.replace(i, 1, buf); + i += 3; + } + } + return txt; +} + /** * Below are a few static members of the LSCPServer class. * The big assumption here is that LSCPServer is going to remain a singleton. @@ -61,7 +105,7 @@ Mutex LSCPServer::SubscriptionMutex = Mutex(); Mutex LSCPServer::RTNotifyMutex = Mutex(); -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) { SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = addr; SocketAddress.sin_port = port; @@ -87,19 +131,79 @@ LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO"); LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO"); LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS"); + LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT"); LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT"); LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO"); + LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI"); + LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI"); hSocket = -1; } LSCPServer::~LSCPServer() { +#if defined(WIN32) + if (hSocket >= 0) closesocket(hSocket); +#else if (hSocket >= 0) close(hSocket); +#endif +} + +LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) { + this->pParent = pParent; +} + +LSCPServer::EventHandler::~EventHandler() { + std::vector l = channelMidiListeners; + channelMidiListeners.clear(); + for (int i = 0; i < l.size(); i++) + delete l[i].pMidiListener; } void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount)); } +void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) { + pChannel->AddEngineChangeListener(this); +} + +void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) { + if (!pChannel->GetEngineChannel()) return; + EngineToBeChanged(pChannel->Index()); +} + +void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) { + SamplerChannel* pSamplerChannel = + pParent->pSampler->GetSamplerChannel(ChannelId); + if (!pSamplerChannel) return; + EngineChannel* pEngineChannel = + pSamplerChannel->GetEngineChannel(); + if (!pEngineChannel) return; + for (std::vector::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) { + if ((*iter).pEngineChannel == pEngineChannel) { + VirtualMidiDevice* pMidiListener = (*iter).pMidiListener; + pEngineChannel->Disconnect(pMidiListener); + channelMidiListeners.erase(iter); + delete pMidiListener; + return; + } + } +} + +void LSCPServer::EventHandler::EngineChanged(int ChannelId) { + SamplerChannel* pSamplerChannel = + pParent->pSampler->GetSamplerChannel(ChannelId); + if (!pSamplerChannel) return; + EngineChannel* pEngineChannel = + pSamplerChannel->GetEngineChannel(); + if (!pEngineChannel) return; + VirtualMidiDevice* pMidiListener = new VirtualMidiDevice; + pEngineChannel->Connect(pMidiListener); + midi_listener_entry entry = { + pSamplerChannel, pEngineChannel, pMidiListener + }; + channelMidiListeners.push_back(entry); +} + void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount)); } @@ -108,6 +212,54 @@ LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount)); } +void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) { + pDevice->RemoveMidiPortCountListener(this); + for (int i = 0; i < pDevice->PortCount(); ++i) + MidiPortToBeRemoved(pDevice->GetPort(i)); +} + +void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) { + pDevice->AddMidiPortCountListener(this); + for (int i = 0; i < pDevice->PortCount(); ++i) + MidiPortAdded(pDevice->GetPort(i)); +} + +void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) { + // yet unused +} + +void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) { + for (std::vector::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) { + if ((*iter).pPort == pPort) { + VirtualMidiDevice* pMidiListener = (*iter).pMidiListener; + pPort->Disconnect(pMidiListener); + deviceMidiListeners.erase(iter); + delete pMidiListener; + return; + } + } +} + +void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) { + // find out the device ID + std::map devices = + pParent->pSampler->GetMidiInputDevices(); + for ( + std::map::iterator iter = devices.begin(); + iter != devices.end(); ++iter + ) { + if (iter->second == pPort->GetDevice()) { // found + VirtualMidiDevice* pMidiListener = new VirtualMidiDevice; + pPort->Connect(pMidiListener); + device_midi_listener_entry entry = { + pPort, pMidiListener, iter->first + }; + deviceMidiListeners.push_back(entry); + return; + } + } +} + void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount)); } @@ -144,6 +296,10 @@ LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount)); } +void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) { + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount)); +} + #if HAVE_SQLITE3 void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir))); @@ -194,6 +350,15 @@ } int LSCPServer::Main() { + #if defined(WIN32) + WSADATA wsaData; + int iResult; + iResult = WSAStartup(MAKEWORD(2,2), &wsaData); + if (iResult != 0) { + std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n"; + exit(EXIT_FAILURE); + } + #endif hSocket = socket(AF_INET, SOCK_STREAM, 0); if (hSocket < 0) { std::cerr << "LSCPServer: Could not create server socket." << std::endl; @@ -207,7 +372,11 @@ if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) { if (trial > LSCP_SERVER_BIND_TIMEOUT) { std::cerr << "gave up!" << std::endl; + #if defined(WIN32) + closesocket(hSocket); + #else close(hSocket); + #endif //return -1; exit(EXIT_FAILURE); } @@ -227,6 +396,7 @@ pSampler->AddVoiceCountListener(&eventHandler); pSampler->AddStreamCountListener(&eventHandler); pSampler->AddBufferFillListener(&eventHandler); + pSampler->AddTotalStreamCountListener(&eventHandler); pSampler->AddTotalVoiceCountListener(&eventHandler); pSampler->AddFxSendCountListener(&eventHandler); MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler); @@ -246,6 +416,9 @@ timeval timeout; while (true) { + #if CONFIG_PTHREAD_TESTCANCEL + TestCancel(); + #endif // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers { std::set engineChannels = EngineChannelFactory::EngineChannelInstances(); @@ -253,13 +426,13 @@ std::set::iterator itEnd = engineChannels.end(); for (; itEngineChannel != itEnd; ++itEngineChannel) { if ((*itEngineChannel)->StatusChanged()) { - SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex)); + SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index())); } for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) { FxSend* fxs = (*itEngineChannel)->GetFxSend(i); if(fxs != NULL && fxs->IsInfoChanged()) { - int chn = (*itEngineChannel)->iSamplerChannelIndex; + int chn = (*itEngineChannel)->GetSamplerChannel()->Index(); LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id())); fxs->SetInfoChanged(false); } @@ -267,6 +440,55 @@ } } + // check if MIDI data arrived on some engine channel + for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) { + const EventHandler::midi_listener_entry entry = + eventHandler.channelMidiListeners[i]; + VirtualMidiDevice* pMidiListener = entry.pMidiListener; + if (pMidiListener->NotesChanged()) { + for (int iNote = 0; iNote < 128; iNote++) { + if (pMidiListener->NoteChanged(iNote)) { + const bool bActive = pMidiListener->NoteIsActive(iNote); + LSCPServer::SendLSCPNotify( + LSCPEvent( + LSCPEvent::event_channel_midi, + entry.pSamplerChannel->Index(), + std::string(bActive ? "NOTE_ON" : "NOTE_OFF"), + iNote, + bActive ? pMidiListener->NoteOnVelocity(iNote) + : pMidiListener->NoteOffVelocity(iNote) + ) + ); + } + } + } + } + + // check if MIDI data arrived on some MIDI device + for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) { + const EventHandler::device_midi_listener_entry entry = + eventHandler.deviceMidiListeners[i]; + VirtualMidiDevice* pMidiListener = entry.pMidiListener; + if (pMidiListener->NotesChanged()) { + for (int iNote = 0; iNote < 128; iNote++) { + if (pMidiListener->NoteChanged(iNote)) { + const bool bActive = pMidiListener->NoteIsActive(iNote); + LSCPServer::SendLSCPNotify( + LSCPEvent( + LSCPEvent::event_device_midi, + entry.uiDeviceID, + entry.pPort->GetPortNumber(), + std::string(bActive ? "NOTE_ON" : "NOTE_OFF"), + iNote, + bActive ? pMidiListener->NoteOnVelocity(iNote) + : pMidiListener->NoteOffVelocity(iNote) + ) + ); + } + } + } + } + //Now let's deliver late notifies (if any) NotifyBufferMutex.Lock(); for (std::map::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) { @@ -289,7 +511,11 @@ continue; //Nothing try again if (retval == -1) { std::cerr << "LSCPServer: Socket select error." << std::endl; + #if defined(WIN32) + closesocket(hSocket); + #else close(hSocket); + #endif exit(EXIT_FAILURE); } @@ -301,10 +527,18 @@ exit(EXIT_FAILURE); } + #if defined(WIN32) + u_long nonblock_io = 1; + if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) { + std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl; + exit(EXIT_FAILURE); + } + #else if (fcntl(socket, F_SETFL, O_NONBLOCK)) { std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl; exit(EXIT_FAILURE); } + #endif // Parser initialization yyparse_param_t yyparse_param; @@ -363,10 +597,22 @@ NotifyMutex.Lock(); bufferedCommands.erase(socket); bufferedNotifies.erase(socket); + #if defined(WIN32) + closesocket(socket); + #else close(socket); + #endif NotifyMutex.Unlock(); } +void LSCPServer::LockRTNotify() { + RTNotifyMutex.Lock(); +} + +void LSCPServer::UnlockRTNotify() { + RTNotifyMutex.Unlock(); +} + int LSCPServer::EventSubscribers( std::list events ) { int subs = 0; SubscriptionMutex.Lock(); @@ -442,7 +688,11 @@ char c; int i = 0; while (true) { + #if defined(WIN32) + int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now + #else int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now + #endif if (result == 0) { //socket was selected, so 0 here means client has closed the connection CloseConnection(iter); break; @@ -457,6 +707,16 @@ } bufferedCommands[socket] += c; } + #if defined(WIN32) + if (result == SOCKET_ERROR) { + int wsa_lasterror = WSAGetLastError(); + if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later. + return false; + dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror)); + CloseConnection(iter); + break; + } + #else if (result == -1) { if (errno == EAGAIN) //Would block, try again later. return false; @@ -495,6 +755,7 @@ CloseConnection(iter); break; } + #endif } return false; } @@ -768,7 +1029,7 @@ LockRTNotify(); try { Engine* pEngine = EngineFactory::Create(EngineName); - result.Add("DESCRIPTION", pEngine->Description()); + result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description())); result.Add("VERSION", pEngine->Version()); EngineFactory::Destroy(pEngine); } @@ -841,9 +1102,20 @@ if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL"); else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel()); + // convert the filename into the correct encoding as defined for LSCP + // (especially in terms of special characters -> escape sequences) + if (InstrumentFileName != "NONE" && InstrumentFileName != "") { +#if WIN32 + InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp(); +#else + // assuming POSIX + InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp(); +#endif + } + result.Add("INSTRUMENT_FILE", InstrumentFileName); result.Add("INSTRUMENT_NR", InstrumentIndex); - result.Add("INSTRUMENT_NAME", InstrumentName); + result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName)); result.Add("INSTRUMENT_STATUS", InstrumentStatus); result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false")); result.Add("SOLO", Solo); @@ -863,10 +1135,7 @@ dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel"); result.Add(pEngineChannel->GetEngine()->VoiceCount()); } @@ -884,10 +1153,7 @@ dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel"); result.Add(pEngineChannel->GetEngine()->DiskStreamCount()); } @@ -905,10 +1171,7 @@ dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel"); if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA"); else { @@ -1586,10 +1849,7 @@ dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); pEngineChannel->Volume(dVolume); } catch (Exception e) { @@ -1605,11 +1865,7 @@ dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0); else pEngineChannel->SetMute(1); @@ -1626,11 +1882,7 @@ dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); bool oldSolo = pEngineChannel->GetSolo(); bool hadSoloChannel = HasSoloChannel(); @@ -1750,7 +2002,7 @@ dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n")); LSCPResultSet result; try { - result.Add(MidiInstrumentMapper::Entries(MidiMapID).size()); + result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID)); } catch (Exception e) { result.Error(e); } @@ -1761,14 +2013,11 @@ String LSCPServer::GetAllMidiInstrumentMappings() { dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n")); LSCPResultSet result; - std::vector maps = MidiInstrumentMapper::Maps(); - int totalMappings = 0; - for (int i = 0; i < maps.size(); i++) { - try { - totalMappings += MidiInstrumentMapper::Entries(maps[i]).size(); - } catch (Exception e) { /*NOOP*/ } + try { + result.Add(MidiInstrumentMapper::GetInstrumentCount()); + } catch (Exception e) { + result.Error(e); } - result.Add(totalMappings); return result.Produce(); } @@ -1776,46 +2025,46 @@ dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n")); LSCPResultSet result; try { - midi_prog_index_t idx; - idx.midi_bank_msb = (MidiBank >> 7) & 0x7f; - idx.midi_bank_lsb = MidiBank & 0x7f; - idx.midi_prog = MidiProg; - - std::map mappings = MidiInstrumentMapper::Entries(MidiMapID); - std::map::iterator iter = mappings.find(idx); - if (iter == mappings.end()) result.Error("there is no map entry with that index"); - else { // found - result.Add("NAME", iter->second.Name); - result.Add("ENGINE_NAME", iter->second.EngineName); - result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile); - result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex); - String instrumentName; - Engine* pEngine = EngineFactory::Create(iter->second.EngineName); - if (pEngine) { - if (pEngine->GetInstrumentManager()) { - InstrumentManager::instrument_id_t instrID; - instrID.FileName = iter->second.InstrumentFile; - instrID.Index = iter->second.InstrumentIndex; - instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID); - } - EngineFactory::Destroy(pEngine); - } - result.Add("INSTRUMENT_NAME", instrumentName); - switch (iter->second.LoadMode) { - case MidiInstrumentMapper::ON_DEMAND: - result.Add("LOAD_MODE", "ON_DEMAND"); - break; - case MidiInstrumentMapper::ON_DEMAND_HOLD: - result.Add("LOAD_MODE", "ON_DEMAND_HOLD"); - break; - case MidiInstrumentMapper::PERSISTENT: - result.Add("LOAD_MODE", "PERSISTENT"); - break; - default: - throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!"); + MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg); + // convert the filename into the correct encoding as defined for LSCP + // (especially in terms of special characters -> escape sequences) +#if WIN32 + const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp(); +#else + // assuming POSIX + const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp(); +#endif + + result.Add("NAME", _escapeLscpResponse(entry.Name)); + result.Add("ENGINE_NAME", entry.EngineName); + result.Add("INSTRUMENT_FILE", instrumentFileName); + result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex); + String instrumentName; + Engine* pEngine = EngineFactory::Create(entry.EngineName); + if (pEngine) { + if (pEngine->GetInstrumentManager()) { + InstrumentManager::instrument_id_t instrID; + instrID.FileName = entry.InstrumentFile; + instrID.Index = entry.InstrumentIndex; + instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID); } - result.Add("VOLUME", iter->second.Volume); + EngineFactory::Destroy(pEngine); } + result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName)); + switch (entry.LoadMode) { + case MidiInstrumentMapper::ON_DEMAND: + result.Add("LOAD_MODE", "ON_DEMAND"); + break; + case MidiInstrumentMapper::ON_DEMAND_HOLD: + result.Add("LOAD_MODE", "ON_DEMAND_HOLD"); + break; + case MidiInstrumentMapper::PERSISTENT: + result.Add("LOAD_MODE", "PERSISTENT"); + break; + default: + throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!"); + } + result.Add("VOLUME", entry.Volume); } catch (Exception e) { result.Error(e); } @@ -1955,7 +2204,7 @@ dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n")); LSCPResultSet result; try { - result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID)); + result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID))); result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID); } catch (Exception e) { result.Error(e); @@ -1986,11 +2235,7 @@ dmsg(2,("LSCPServer: SetChannelMap()\n")); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone(); else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault(); @@ -2099,7 +2344,7 @@ } // success - result.Add("NAME", pFxSend->Name()); + result.Add("NAME", _escapeLscpResponse(pFxSend->Name())); result.Add("MIDI_CONTROLLER", pFxSend->MidiController()); result.Add("LEVEL", ToString(pFxSend->Level())); result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting); @@ -2169,10 +2414,7 @@ dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel"); Engine* pEngine = pEngineChannel->GetEngine(); InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager(); @@ -2187,6 +2429,42 @@ return result.Produce(); } +String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) { + dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2)); + LSCPResultSet result; + try { + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); + + if (Arg1 > 127 || Arg2 > 127) { + throw Exception("Invalid MIDI message"); + } + + VirtualMidiDevice* pMidiDevice = NULL; + std::vector::iterator iter = eventHandler.channelMidiListeners.begin(); + for (; iter != eventHandler.channelMidiListeners.end(); ++iter) { + if ((*iter).pEngineChannel == pEngineChannel) { + pMidiDevice = (*iter).pMidiListener; + break; + } + } + + if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device"); + + if (MidiMsg == "NOTE_ON") { + bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2); + if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2)); + } else if (MidiMsg == "NOTE_OFF") { + bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2); + if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2)); + } else { + throw Exception("Unknown MIDI message type: " + MidiMsg); + } + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + /** * Will be called by the parser to reset a particular sampler channel. */ @@ -2194,10 +2472,7 @@ dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(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"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); pEngineChannel->Reset(); } catch (Exception e) { @@ -2222,8 +2497,10 @@ */ String LSCPServer::GetServerInfo() { dmsg(2,("LSCPServer: GetServerInfo()\n")); + const std::string description = + _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler"); LSCPResultSet result; - result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler"); + result.Add("DESCRIPTION", description); result.Add("VERSION", VERSION); result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR)); #if HAVE_SQLITE3 @@ -2236,6 +2513,16 @@ } /** + * Will be called by the parser to return the current number of all active streams. + */ +String LSCPServer::GetTotalStreamCount() { + dmsg(2,("LSCPServer: GetTotalStreamCount()\n")); + LSCPResultSet result; + result.Add(pSampler->GetDiskStreamCount()); + return result.Produce(); +} + +/** * Will be called by the parser to return the current number of all active voices. */ String LSCPServer::GetTotalVoiceCount() { @@ -2265,7 +2552,7 @@ LSCPResultSet result; try { if (dVolume < 0) throw Exception("Volume may not be negative"); - GLOBAL_VOLUME = dVolume; // see common/global.cpp + GLOBAL_VOLUME = dVolume; // see common/global_private.cpp LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME)); } catch (Exception e) { result.Error(e); @@ -2273,6 +2560,185 @@ return result.Produce(); } +String LSCPServer::GetFileInstruments(String Filename) { + dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str())); + LSCPResultSet result; + try { + VerifyFile(Filename); + } catch (Exception e) { + result.Error(e); + return result.Produce(); + } + // try to find a sampler engine that can handle the file + bool bFound = false; + std::vector engineTypes = EngineFactory::AvailableEngineTypes(); + for (int i = 0; !bFound && i < engineTypes.size(); i++) { + Engine* pEngine = NULL; + try { + pEngine = EngineFactory::Create(engineTypes[i]); + if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine"); + InstrumentManager* pManager = pEngine->GetInstrumentManager(); + if (pManager) { + std::vector IDs = + pManager->GetInstrumentFileContent(Filename); + // return the amount of instruments in the file + result.Add(IDs.size()); + // no more need to ask other engine types + bFound = true; + } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str())); + } catch (Exception e) { + // NOOP, as exception is thrown if engine doesn't support file + } + if (pEngine) EngineFactory::Destroy(pEngine); + } + + if (!bFound) result.Error("Unknown file format"); + return result.Produce(); +} + +String LSCPServer::ListFileInstruments(String Filename) { + dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str())); + LSCPResultSet result; + try { + VerifyFile(Filename); + } catch (Exception e) { + result.Error(e); + return result.Produce(); + } + // try to find a sampler engine that can handle the file + bool bFound = false; + std::vector engineTypes = EngineFactory::AvailableEngineTypes(); + for (int i = 0; !bFound && i < engineTypes.size(); i++) { + Engine* pEngine = NULL; + try { + pEngine = EngineFactory::Create(engineTypes[i]); + if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine"); + InstrumentManager* pManager = pEngine->GetInstrumentManager(); + if (pManager) { + std::vector IDs = + pManager->GetInstrumentFileContent(Filename); + // return a list of IDs of the instruments in the file + String s; + for (int j = 0; j < IDs.size(); j++) { + if (s.size()) s += ","; + s += ToString(IDs[j].Index); + } + result.Add(s); + // no more need to ask other engine types + bFound = true; + } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str())); + } catch (Exception e) { + // NOOP, as exception is thrown if engine doesn't support file + } + if (pEngine) EngineFactory::Destroy(pEngine); + } + + if (!bFound) result.Error("Unknown file format"); + return result.Produce(); +} + +String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) { + dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID)); + LSCPResultSet result; + try { + VerifyFile(Filename); + } catch (Exception e) { + result.Error(e); + return result.Produce(); + } + InstrumentManager::instrument_id_t id; + id.FileName = Filename; + id.Index = InstrumentID; + // try to find a sampler engine that can handle the file + bool bFound = false; + bool bFatalErr = false; + std::vector engineTypes = EngineFactory::AvailableEngineTypes(); + for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) { + Engine* pEngine = NULL; + try { + pEngine = EngineFactory::Create(engineTypes[i]); + if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine"); + InstrumentManager* pManager = pEngine->GetInstrumentManager(); + if (pManager) { + // check if the instrument index is valid + // FIXME: this won't work if an engine only supports parts of the instrument file + std::vector IDs = + pManager->GetInstrumentFileContent(Filename); + if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) { + std::stringstream ss; + ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'"; + bFatalErr = true; + throw Exception(ss.str()); + } + // get the info of the requested instrument + InstrumentManager::instrument_info_t info = + pManager->GetInstrumentInfo(id); + // return detailed informations about the file + result.Add("NAME", info.InstrumentName); + result.Add("FORMAT_FAMILY", engineTypes[i]); + result.Add("FORMAT_VERSION", info.FormatVersion); + result.Add("PRODUCT", info.Product); + result.Add("ARTISTS", info.Artists); + + std::stringstream ss; + bool b = false; + for (int i = 0; i < 128; i++) { + if (info.KeyBindings[i]) { + if (b) ss << ','; + ss << i; b = true; + } + } + result.Add("KEY_BINDINGS", ss.str()); + + std::stringstream ss2; + for (int i = 0; i < 128; i++) { + if (info.KeySwitchBindings[i]) { + if (b) ss2 << ','; + ss2 << i; b = true; + } + } + result.Add("KEYSWITCH_BINDINGS", ss2.str()); + // no more need to ask other engine types + bFound = true; + } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str())); + } catch (Exception e) { + // usually NOOP, as exception is thrown if engine doesn't support file + if (bFatalErr) result.Error(e); + } + if (pEngine) EngineFactory::Destroy(pEngine); + } + + if (!bFound && !bFatalErr) result.Error("Unknown file format"); + return result.Produce(); +} + +void LSCPServer::VerifyFile(String Filename) { + #if WIN32 + WIN32_FIND_DATA win32FileAttributeData; + BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData ); + if (!res) { + std::stringstream ss; + ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError(); + throw Exception(ss.str()); + } + if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { + throw Exception("Directory is specified"); + } + #else + struct stat statBuf; + int res = stat(Filename.c_str(), &statBuf); + if (res) { + std::stringstream ss; + ss << "Fail to stat `" << Filename << "`: " << strerror(errno); + throw Exception(ss.str()); + } + + if (S_ISDIR(statBuf.st_mode)) { + throw Exception("Directory is specified"); + } + #endif +} + /** * Will be called by the parser to subscribe a client (frontend) on the * server for receiving event messages. @@ -2374,7 +2840,7 @@ try { DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir); - result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description)); + result.Add("DESCRIPTION", _escapeLscpResponse(info.Description)); result.Add("CREATED", info.Created); result.Add("MODIFIED", info.Modified); } catch (Exception e) { @@ -2558,11 +3024,11 @@ result.Add("SIZE", (int)info.Size); result.Add("CREATED", info.Created); result.Add("MODIFIED", info.Modified); - result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description)); + result.Add("DESCRIPTION", _escapeLscpResponse(info.Description)); result.Add("IS_DRUM", info.IsDrum); - result.Add("PRODUCT", InstrumentsDb::toEscapedText(info.Product)); - result.Add("ARTISTS", InstrumentsDb::toEscapedText(info.Artists)); - result.Add("KEYWORDS", InstrumentsDb::toEscapedText(info.Keywords)); + result.Add("PRODUCT", _escapeLscpResponse(info.Product)); + result.Add("ARTISTS", _escapeLscpResponse(info.Artists)); + result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords)); } catch (Exception e) { result.Error(e); } @@ -2652,6 +3118,44 @@ return result.Produce(); } +String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) { + dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str())); + LSCPResultSet result; +#if HAVE_SQLITE3 + try { + InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath); + } catch (Exception e) { + result.Error(e); + } +#else + result.Error(String(DOESNT_HAVE_SQLITE3), 0); +#endif + return result.Produce(); +} + +String LSCPServer::FindLostDbInstrumentFiles() { + dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n")); + LSCPResultSet result; +#if HAVE_SQLITE3 + try { + String list; + StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles(); + + for (int i = 0; i < pLostFiles->size(); i++) { + if (list != "") list += ","; + list += "'" + pLostFiles->at(i) + "'"; + } + + result.Add(list); + } catch (Exception e) { + result.Error(e); + } +#else + result.Error(String(DOESNT_HAVE_SQLITE3), 0); +#endif + return result.Produce(); +} + String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map Parameters, bool Recursive) { dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str())); LSCPResultSet result; @@ -2748,6 +3252,21 @@ return result.Produce(); } +String LSCPServer::FormatInstrumentsDb() { + dmsg(2,("LSCPServer: FormatInstrumentsDb()\n")); + LSCPResultSet result; +#if HAVE_SQLITE3 + try { + InstrumentsDb::GetInstrumentsDb()->Format(); + } catch (Exception e) { + result.Error(e); + } +#else + result.Error(String(DOESNT_HAVE_SQLITE3), 0); +#endif + return result.Produce(); +} + /** * Will be called by the parser to enable or disable echo mode; if echo @@ -2767,3 +3286,5 @@ } return result.Produce(); } + +}