Skip to content

Instantly share code, notes, and snippets.

@Xenakios
Created January 15, 2025 17:23
Show Gist options
  • Save Xenakios/0ebd2b2c33b0446673d8506b75f202d8 to your computer and use it in GitHub Desktop.
Save Xenakios/0ebd2b2c33b0446673d8506b75f202d8 to your computer and use it in GitHub Desktop.
namespace sst::osc_adapter
{
struct OSCAdapter
{
OSCAdapter(const clap_plugin *p); // bind to this plugin
const clap_input_events *getInputEventQueue() { return eventList.clapInputEvents(); }
clap_output_events *getOutputEventQueue(); // auto thread event queue
void startWith(uint32_t inputPort, uint32_t outputPort)
{
oscThreadShouldStop = false;
oscThread =
std::make_unique<std::thread>([=, this]() { runOscThread(inputPort, outputPort); });
}
void stop()
{
oscThreadShouldStop = true;
if (oscThread)
{
oscThread->join();
oscThread = nullptr;
}
}
void runOscThread(uint32_t inputPort, uint32_t outputPort)
{
using namespace oscpkt;
UdpSocket sock;
sock.bindTo(inputPort);
if (!sock.isOk())
{
std::cout << "Error opening port " << inputPort << ": " << sock.errorMessage() << "\n";
return;
}
std::cout << "Server started, will listen to packets on port " << inputPort << std::endl;
PacketReader pr;
PacketWriter pw;
while (!oscThreadShouldStop)
{
if (!sock.isOk())
{
break;
}
if (sock.receiveNextPacket(30))
{
pr.init(sock.packetData(), sock.packetSize());
oscpkt::Message *msg = nullptr;
while (pr.isOk() && (msg = pr.popMessage()) != nullptr)
{
int64_t iarg0 = CLAP_INVALID_ID;
double darg0 = 0.0;
if (msg->match("/set_parameter")
.popInt64(iarg0)
.popDouble(darg0)
.isOkNoMoreArgs())
{
// constructing clap events like this is a bit verbose,
// will probably want some kind of abstraction for this
clap_event_param_value pev;
pev.header.flags = 0;
pev.header.size = sizeof(clap_event_param_value);
pev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
pev.header.time = 0;
pev.header.type = CLAP_EVENT_PARAM_VALUE;
pev.cookie = nullptr; // to be nice, should implement this properly
pev.channel = -1;
pev.port_index = -1;
pev.key = -1;
pev.param_id = iarg0;
pev.value = darg0;
eventList.push((const clap_event_header *)&pev);
}
}
}
}
}
std::unique_ptr<std::thread> oscThread;
std::atomic<bool> oscThreadShouldStop{false};
clap::helpers::EventList eventList;
};
} // namespace sst::osc_adapter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment