-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTriggerOutput.h
More file actions
384 lines (332 loc) · 13.9 KB
/
TriggerOutput.h
File metadata and controls
384 lines (332 loc) · 13.9 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
#pragma once
#include <JuceHeader.h>
#include <atomic>
#include "OscSender.h"
#include "AppSettings.h"
//==============================================================================
// TriggerOutput -- Dispatches MIDI and OSC messages on track changes.
//
// Owned by TimecodeEngine, one per engine instance.
// When a track change is detected and the track has triggers configured,
// fires the appropriate MIDI and/or OSC messages.
//
// MIDI output device is independent from MTC output.
//==============================================================================
class TriggerOutput
{
public:
TriggerOutput() = default;
~TriggerOutput() { stopMidi(); }
//--------------------------------------------------------------------------
// MIDI output device management
//--------------------------------------------------------------------------
void refreshMidiDevices()
{
midiDevices = juce::MidiOutput::getAvailableDevices();
}
int getMidiDeviceCount() const { return (int)midiDevices.size(); }
juce::String getMidiDeviceName(int index) const
{
if (index >= 0 && index < (int)midiDevices.size())
return midiDevices[index].name;
return {};
}
int findMidiDeviceByName(const juce::String& name) const
{
for (int i = 0; i < (int)midiDevices.size(); ++i)
if (midiDevices[i].name == name)
return i;
return -1;
}
bool startMidi(int deviceIndex)
{
stopMidi();
if (deviceIndex < 0 || deviceIndex >= (int)midiDevices.size())
return false;
midiOutput = juce::MidiOutput::openDevice(midiDevices[deviceIndex].identifier);
if (midiOutput)
{
currentMidiDeviceName = midiDevices[deviceIndex].name;
return true;
}
return false;
}
bool startMidiByName(const juce::String& name)
{
refreshMidiDevices();
int idx = findMidiDeviceByName(name);
return idx >= 0 && startMidi(idx);
}
void stopMidi()
{
clockTimer.stop();
sharedMidiOut = nullptr; // release borrowed pointer (not owned)
midiOutput.reset(); // close own device if open
currentMidiDeviceName.clear();
}
bool isMidiOpen() const { return getActiveMidi() != nullptr; }
bool hasOwnMidiOpen() const { return midiOutput != nullptr; }
juce::String getCurrentMidiDeviceName() const { return currentMidiDeviceName; }
//--------------------------------------------------------------------------
// Shared MIDI output -- allows TriggerOutput to piggyback on MtcOutput's
// open device handle when both target the same MIDI port.
// juce::MidiOutput::sendMessageNow() is thread-safe (internal CriticalSection).
//--------------------------------------------------------------------------
/// Set an external MidiOutput to use instead of (or alongside) our own.
/// Pass nullptr to clear and fall back to own device.
void setSharedMidiOutput(juce::MidiOutput* shared)
{
sharedMidiOut = shared;
// If sharing and clock is running, redirect it to the shared output
if (shared && clockTimer.isTimerRunning())
clockTimer.updateOutput(shared);
}
/// Close our OWN MidiOutput handle (if open) without affecting the shared pointer.
/// Used before MtcOutput opens the same device to avoid double-open conflict.
void releaseOwnMidi()
{
if (midiOutput)
{
// If clock was using our own output, redirect to shared (if available)
if (clockTimer.isTimerRunning())
{
if (sharedMidiOut)
clockTimer.updateOutput(sharedMidiOut);
else
clockTimer.stop();
}
midiOutput.reset();
}
}
//--------------------------------------------------------------------------
// OSC destination management
//--------------------------------------------------------------------------
bool connectOsc(const juce::String& ip, int port)
{
oscIp = ip;
oscPort = port;
return oscSender.connect(ip, port);
}
void disconnectOsc() { oscSender.disconnect(); }
bool isOscConnected() const { return oscSender.isConnected(); }
void updateOscDestination(const juce::String& ip, int port)
{
if (ip != oscIp || port != oscPort)
{
oscIp = ip;
oscPort = port;
if (oscSender.isConnected())
oscSender.connect(ip, port); // reconnect to new dest
}
}
juce::String getOscDestination() const
{
return oscIp + ":" + juce::String(oscPort);
}
//--------------------------------------------------------------------------
// Enable flags
//--------------------------------------------------------------------------
void setMidiEnabled(bool enabled) { midiEnabled = enabled; }
void setOscEnabled(bool enabled) { oscEnabled = enabled; }
bool isMidiEnabled() const { return midiEnabled; }
bool isOscEnabled() const { return oscEnabled; }
//--------------------------------------------------------------------------
// Fire trigger for a track change
//--------------------------------------------------------------------------
/// Call this when a track change is detected and the entry is found in TrackMap.
/// Sends MIDI and/or OSC based on the entry's per-track config and the
/// global enable flags.
///
/// NOTE: This method is called from TimecodeEngine::tick() which runs on the
/// JUCE message thread (60Hz timer callback). sendMessageNow() is synchronous
/// and may briefly block (~microseconds on healthy drivers). For Note On +
/// Note Off back-to-back, two synchronous calls are made. This is acceptable
/// for show control trigger use cases but could cause a UI stutter if a MIDI
/// driver is exceptionally slow.
void fire(const TrackMapEntry& entry)
{
if (midiEnabled)
fireMidi(entry);
if (oscEnabled)
fireOsc(entry);
lastFiredTrackKey = entry.key();
}
std::string getLastFiredTrackKey() const { return lastFiredTrackKey; }
//--------------------------------------------------------------------------
// Continuous control forwarding (crossfader, BPM)
// Called from TimecodeEngine tick -- sends MIDI CC and/or OSC
//--------------------------------------------------------------------------
/// Send a MIDI CC message. Channel is 1-based (1-16).
/// Only sends if MIDI output is open (ignores midiEnabled flag --
/// CC forward has its own enable).
void sendCC(int channel, int cc, int value)
{
auto* midi = getActiveMidi();
if (!midi) return;
auto msg = juce::MidiMessage::controllerEvent(
juce::jlimit(1, 16, channel),
juce::jlimit(0, 127, cc),
juce::jlimit(0, 127, value));
midi->sendMessageNow(msg);
}
/// Send a MIDI Note On message for continuous fader control.
/// Channel is 1-based (1-16), note 0-127, velocity 0-127.
/// Used by grandMA2/MA3: note = executor number, velocity = fader position.
/// No Note Off is sent -- velocity 0 is the "fader closed" state and
/// sending Note Off would reset the receiver to an undefined state.
void sendNote(int channel, int note, int velocity)
{
auto* midi = getActiveMidi();
if (!midi) return;
auto msg = juce::MidiMessage::noteOn(
juce::jlimit(1, 16, channel),
juce::jlimit(0, 127, note),
(uint8_t)juce::jlimit(0, 127, velocity));
midi->sendMessageNow(msg);
}
/// Send a raw OSC message with a single float value.
/// Uses the zero-allocation fast path -- no String creation, no tokenization.
/// The connected check is inside sendFloatDirect (single lock acquisition).
void sendOscFloat(const juce::String& address, float value)
{
oscSender.sendFloatDirect(address, value);
}
//--------------------------------------------------------------------------
// MIDI Clock -- 24 pulses per quarter note at the current BPM.
// Runs on a dedicated HighResolutionTimer thread (1ms tick).
// Uses a fractional accumulator for drift-free pulse timing.
//--------------------------------------------------------------------------
void startMidiClock(double bpm)
{
auto* midi = getActiveMidi();
if (!midi) return;
clockTimer.start(bpm, midi);
}
void stopMidiClock()
{
clockTimer.stop();
}
void updateMidiClockBpm(double bpm)
{
clockTimer.setBpm(bpm);
}
bool isMidiClockRunning() const { return clockTimer.isTimerRunning(); }
private:
//--------------------------------------------------------------------------
// MIDI Clock timer -- 1ms resolution, fractional accumulator
//--------------------------------------------------------------------------
class MidiClockTimer : public juce::HighResolutionTimer
{
public:
MidiClockTimer() = default;
~MidiClockTimer() override { stopTimer(); }
void start(double bpm, juce::MidiOutput* output)
{
midiOut.store(output, std::memory_order_relaxed);
setBpm(bpm);
accumulator = 0.0;
// Send MIDI Start (0xFA)
if (output) output->sendMessageNow(juce::MidiMessage(0xFA));
startTimer(1);
}
void stop()
{
stopTimer();
// Send MIDI Stop (0xFC)
auto* out = midiOut.load(std::memory_order_relaxed);
if (out) out->sendMessageNow(juce::MidiMessage(0xFC));
midiOut.store(nullptr, std::memory_order_relaxed);
}
void setBpm(double bpm)
{
if (bpm >= 20.0 && bpm <= 999.0)
pulsesPerMs.store(bpm * 24.0 / 60000.0, std::memory_order_relaxed);
}
/// Redirect clock output to a different MidiOutput (e.g. when switching
/// from own device to shared MtcOutput device). Now truly thread-safe
/// via atomic store -- timer thread reads via atomic load.
void updateOutput(juce::MidiOutput* newOut) { midiOut.store(newOut, std::memory_order_relaxed); }
void hiResTimerCallback() override
{
double ppms = pulsesPerMs.load(std::memory_order_relaxed);
auto* out = midiOut.load(std::memory_order_relaxed);
if (ppms <= 0.0 || !out) return;
accumulator += ppms;
while (accumulator >= 1.0)
{
out->sendMessageNow(juce::MidiMessage((uint8_t)0xF8));
accumulator -= 1.0;
}
}
private:
std::atomic<juce::MidiOutput*> midiOut { nullptr };
std::atomic<double> pulsesPerMs { 0.048 }; // default 120 BPM
double accumulator = 0.0;
};
MidiClockTimer clockTimer;
//--------------------------------------------------------------------------
// MIDI dispatch
//--------------------------------------------------------------------------
void fireMidi(const TrackMapEntry& entry)
{
auto* midi = getActiveMidi();
if (!midi || !entry.hasMidiTrigger()) return;
int ch = juce::jlimit(0, 15, entry.midiChannel) + 1; // 1-based for JUCE
// Note On: fire-and-forget trigger (Note On + immediate Note Off).
// Zero-duration notes are standard for lighting/show control triggers.
if (entry.midiNoteNum >= 0)
{
int note = juce::jlimit(0, 127, entry.midiNoteNum);
int vel = juce::jlimit(0, 127, entry.midiNoteVel);
midi->sendMessageNow(juce::MidiMessage::noteOn(ch, note, (uint8_t)vel));
midi->sendMessageNow(juce::MidiMessage::noteOff(ch, note));
}
// Control Change
if (entry.midiCCNum >= 0)
{
int cc = juce::jlimit(0, 127, entry.midiCCNum);
int val = juce::jlimit(0, 127, entry.midiCCVal);
midi->sendMessageNow(juce::MidiMessage::controllerEvent(ch, cc, val));
}
}
//--------------------------------------------------------------------------
// OSC dispatch
//--------------------------------------------------------------------------
void fireOsc(const TrackMapEntry& entry)
{
if (!oscSender.isConnected() || !entry.hasOscTrigger()) return;
// Expand built-in variables in oscArgs:
// {artist} -> artist string (quoted for space safety)
// {title} -> title string (quoted for space safety)
// {offset} -> timecode offset string
juce::String args = entry.oscArgs;
args = args.replace("{artist}", "s:\"" + entry.artist + "\"");
args = args.replace("{title}", "s:\"" + entry.title + "\"");
args = args.replace("{offset}", "s:\"" + entry.timecodeOffset + "\"");
oscSender.send(entry.oscAddress, args);
}
//--------------------------------------------------------------------------
// Members
//--------------------------------------------------------------------------
// MIDI
std::unique_ptr<juce::MidiOutput> midiOutput; // own device (when not sharing)
juce::MidiOutput* sharedMidiOut = nullptr; // borrowed from MtcOutput (not owned)
juce::Array<juce::MidiDeviceInfo> midiDevices;
juce::String currentMidiDeviceName;
bool midiEnabled = false;
/// Returns the active MidiOutput: shared if set, else own.
juce::MidiOutput* getActiveMidi() const
{
return sharedMidiOut ? sharedMidiOut : midiOutput.get();
}
// OSC
OscSender oscSender;
juce::String oscIp = "127.0.0.1";
int oscPort = 53000;
bool oscEnabled = false;
std::string lastFiredTrackKey;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(TriggerOutput)
};