-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathOscSender.h
More file actions
261 lines (223 loc) · 8.89 KB
/
OscSender.h
File metadata and controls
261 lines (223 loc) · 8.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
#pragma once
#include <JuceHeader.h>
//==============================================================================
// OscSender -- Lightweight OSC message sender over UDP.
//
// Builds and sends OSC-formatted UDP packets.
// Supports: int32 (i), float32 (f), string (s) argument types.
//
// Usage:
// OscSender osc;
// osc.connect("127.0.0.1", 53000);
// osc.send("/cue/1/go"); // no args
// osc.send("/track/change", "i:42 s:Strobe"); // typed args
//==============================================================================
class OscSender
{
public:
OscSender() = default;
~OscSender() { disconnect(); }
//--------------------------------------------------------------------------
// Connection
//--------------------------------------------------------------------------
bool connect(const juce::String& ip, int port)
{
juce::SpinLock::ScopedLockType lock(socketLock);
socket.reset();
connected = false;
destIp = ip;
destPort = port;
socket = std::make_unique<juce::DatagramSocket>(false);
// Bind to any local port (ephemeral)
if (!socket->bindToPort(0))
{
socket.reset();
return false;
}
connected = true;
return true;
}
void disconnect()
{
juce::SpinLock::ScopedLockType lock(socketLock);
socket.reset();
connected = false;
}
bool isConnected() const
{
juce::SpinLock::ScopedLockType lock(socketLock);
return connected;
}
void setDestination(const juce::String& ip, int port)
{
juce::SpinLock::ScopedLockType lock(socketLock);
destIp = ip;
destPort = port;
}
//--------------------------------------------------------------------------
// Send an OSC message
//--------------------------------------------------------------------------
/// Send with pre-parsed args string: "i:42 s:hello f:3.14"
/// Each token is "type:value" separated by spaces.
/// Supported types: i (int32), f (float32), s (string)
bool send(const juce::String& address, const juce::String& argsString = {})
{
if (address.isEmpty()) return false;
// Build the packet outside the lock (CPU-only, no shared state)
juce::MemoryBlock packet;
// 1. Write address pattern (null-terminated, padded to 4 bytes)
writeOscString(packet, address);
// 2. Parse args and build type tag + arg data
juce::MemoryBlock argData;
juce::String typeTags = ",";
if (argsString.isNotEmpty())
{
auto tokens = juce::StringArray::fromTokens(argsString, " ", "\"");
for (auto& token : tokens)
{
if (token.isEmpty()) continue;
if (token.length() < 3 || token[1] != ':')
{
DBG("OscSender: skipping malformed arg token: " + token);
continue;
}
auto typeChar = static_cast<char>(token[0]);
auto value = token.substring(2);
switch (typeChar)
{
case 'i':
{
typeTags += "i";
int32_t val = (int32_t)value.getIntValue();
writeInt32(argData, val);
break;
}
case 'f':
{
typeTags += "f";
float val = value.getFloatValue();
writeFloat32(argData, val);
break;
}
case 's':
{
typeTags += "s";
// Strip surrounding quotes if present (used for values with spaces)
if (value.startsWithChar('"') && value.endsWithChar('"') && value.length() >= 2)
value = value.substring(1, value.length() - 1);
writeOscString(argData, value);
break;
}
default:
DBG("OscSender: unknown arg type '" + juce::String::charToString(typeChar)
+ "' in token: " + token);
break; // Unknown type -- skip
}
}
}
// 3. Write type tag string
writeOscString(packet, typeTags);
// 4. Append arg data
packet.append(argData.getData(), argData.getSize());
// 5. Send under lock (protects socket pointer against concurrent disconnect)
juce::SpinLock::ScopedLockType lock(socketLock);
if (!connected || !socket) return false;
return socket->write(destIp, destPort,
packet.getData(), (int)packet.getSize()) > 0;
}
/// Convenience: send with a single int32 argument
bool sendInt(const juce::String& address, int32_t value)
{
return send(address, "i:" + juce::String(value));
}
/// Convenience: send with a single float argument
bool sendFloat(const juce::String& address, float value)
{
return send(address, "f:" + juce::String(value));
}
/// Zero-allocation fast path for sending a single float.
/// Builds the OSC packet in a stack buffer -- no juce::String creation,
/// no MemoryBlock, no tokenization. Used by mixer forwarding hot path.
bool sendFloatDirect(const juce::String& address, float value)
{
if (address.isEmpty()) return false;
auto utf8 = address.toRawUTF8();
size_t addrLen = std::strlen(utf8) + 1; // include null
size_t addrPadded = (addrLen + 3) & ~(size_t)3; // pad to 4
// Max packet: 128-byte address + 4-byte type tag + 4-byte float
// Stack buffer is generous to avoid any edge case.
constexpr size_t kMaxPacket = 256;
if (addrPadded + 8 > kMaxPacket) return false; // address too long
uint8_t packet[kMaxPacket];
std::memset(packet, 0, addrPadded + 8);
// 1. Address string (null-padded to 4-byte boundary)
std::memcpy(packet, utf8, addrLen);
// 2. Type tag ",f" (null-padded to 4 bytes)
size_t off = addrPadded;
packet[off] = ',';
packet[off + 1] = 'f';
// packet[off + 2] and [off + 3] already 0
// 3. Float32 big-endian
off += 4;
int32_t asInt;
std::memcpy(&asInt, &value, 4);
packet[off] = (uint8_t)((asInt >> 24) & 0xFF);
packet[off + 1] = (uint8_t)((asInt >> 16) & 0xFF);
packet[off + 2] = (uint8_t)((asInt >> 8) & 0xFF);
packet[off + 3] = (uint8_t)(asInt & 0xFF);
int totalSize = (int)(addrPadded + 8);
juce::SpinLock::ScopedLockType lock(socketLock);
if (!connected || !socket) return false;
return socket->write(destIp, destPort, packet, totalSize) > 0;
}
/// Convenience: send with a single string argument
bool sendString(const juce::String& address, const juce::String& value)
{
return send(address, "s:\"" + value + "\"");
}
private:
mutable juce::SpinLock socketLock; // protects socket + connected + dest
std::unique_ptr<juce::DatagramSocket> socket;
juce::String destIp = "127.0.0.1";
int destPort = 53000;
bool connected = false;
//--------------------------------------------------------------------------
// OSC encoding helpers
//--------------------------------------------------------------------------
/// Write a null-terminated string padded to 4-byte boundary
static void writeOscString(juce::MemoryBlock& block, const juce::String& s)
{
auto utf8 = s.toRawUTF8();
size_t len = std::strlen(utf8) + 1; // include null terminator
size_t padded = (len + 3) & ~(size_t)3; // round up to 4-byte boundary
block.append(utf8, len);
// Pad with zeros
while (len < padded)
{
block.append("\0", 1);
++len;
}
}
/// Write a big-endian int32
static void writeInt32(juce::MemoryBlock& block, int32_t val)
{
uint8_t bytes[4];
bytes[0] = (uint8_t)((val >> 24) & 0xFF);
bytes[1] = (uint8_t)((val >> 16) & 0xFF);
bytes[2] = (uint8_t)((val >> 8) & 0xFF);
bytes[3] = (uint8_t)(val & 0xFF);
block.append(bytes, 4);
}
/// Write a big-endian float32 (IEEE 754)
static void writeFloat32(juce::MemoryBlock& block, float val)
{
static_assert(sizeof(float) == 4, "float must be 4 bytes");
int32_t asInt;
std::memcpy(&asInt, &val, 4);
writeInt32(block, asInt);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(OscSender)
};