-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMtcOutput.h
More file actions
338 lines (288 loc) · 12.7 KB
/
MtcOutput.h
File metadata and controls
338 lines (288 loc) · 12.7 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
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
#pragma once
#include <JuceHeader.h>
#include "TimecodeCore.h"
#include <atomic>
class MtcOutput : public juce::HighResolutionTimer
{
public:
MtcOutput() = default;
~MtcOutput() override
{
stop();
}
//==============================================================================
juce::StringArray getDeviceNames() const
{
juce::StringArray names;
for (auto& d : availableDevices)
names.add(d.name);
return names;
}
int getDeviceCount() const { return availableDevices.size(); }
juce::String getCurrentDeviceName() const
{
if (currentDeviceIndex >= 0 && currentDeviceIndex < availableDevices.size())
return availableDevices[currentDeviceIndex].name;
return "None";
}
void refreshDeviceList()
{
availableDevices = juce::MidiOutput::getAvailableDevices();
}
//==============================================================================
bool start(int deviceIndex)
{
stop();
if (deviceIndex < 0 || deviceIndex >= availableDevices.size())
return false;
midiOutput = juce::MidiOutput::openDevice(availableDevices[deviceIndex].identifier);
if (midiOutput != nullptr)
{
currentDeviceIndex = deviceIndex;
isRunningFlag.store(true, std::memory_order_relaxed);
paused.store(false, std::memory_order_relaxed);
currentQFIndex.store(0, std::memory_order_relaxed);
mtcSeeded = false;
// Full Frame is sent after the first setTimecode() call populates
// pendingTimecode -- avoids transmitting a misleading 00:00:00.00
// to receivers before the real timecode is available.
// Receivers will sync within 8 QFs (~2 frames) regardless.
lastQfSendTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
updateTimerRate();
return true;
}
return false;
}
void stop()
{
stopTimer();
midiOutput = nullptr;
isRunningFlag.store(false, std::memory_order_relaxed);
paused.store(false, std::memory_order_relaxed);
currentDeviceIndex = -1;
}
bool getIsRunning() const { return isRunningFlag.load(std::memory_order_relaxed); }
/// Raw pointer to the open MidiOutput device (for sharing with TriggerOutput).
/// Returns nullptr if not running. Thread-safe: juce::MidiOutput::sendMessageNow()
/// uses an internal CriticalSection.
juce::MidiOutput* getMidiOutputPtr() const { return midiOutput.get(); }
//==============================================================================
// Called from UI thread - thread-safe via SpinLock
void setTimecode(const Timecode& tc)
{
const juce::SpinLock::ScopedLockType lock(tcLock);
pendingTimecode = tc;
}
// Called from UI thread. startTimer() is internally serialised in JUCE's
// HighResolutionTimer, so calling it from the message thread is safe.
void setFrameRate(FrameRate fps)
{
auto prev = currentFps.load(std::memory_order_relaxed);
if (prev != fps)
{
currentFps.store(fps, std::memory_order_relaxed);
if (isRunningFlag.load(std::memory_order_relaxed) && !paused.load(std::memory_order_relaxed))
updateTimerRate();
}
}
void setPaused(bool shouldPause)
{
if (paused.load(std::memory_order_relaxed) == shouldPause)
return;
if (shouldPause)
{
paused.store(true, std::memory_order_relaxed);
stopTimer();
}
else if (isRunningFlag.load(std::memory_order_relaxed))
{
stopTimer();
currentQFIndex.store(0, std::memory_order_relaxed);
paused.store(false, std::memory_order_relaxed);
mtcSeeded = false;
// Re-sync receivers after pause with a Full Frame message
sendFullFrame();
lastQfSendTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
updateTimerRate();
}
else
{
paused.store(false, std::memory_order_relaxed);
}
}
bool isPaused() const { return paused.load(std::memory_order_relaxed); }
/// Force immediate Full Frame re-sync.
/// Call on seek/hot cue/track change so receivers know the new position
/// instantly instead of waiting 8 QFs (2 frames) to reconstruct it.
void forceResync()
{
if (!isRunningFlag.load(std::memory_order_relaxed)
|| paused.load(std::memory_order_relaxed))
return;
// Reset QF cycle to start fresh from the new position
currentQFIndex.store(0, std::memory_order_relaxed);
mtcSeeded = false;
sendFullFrame();
}
//==============================================================================
void sendFullFrame()
{
if (midiOutput == nullptr)
return;
Timecode tc;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
tc = pendingTimecode;
}
// Single atomic read -- guarantees maxFrames and rateCode are consistent
FrameRate fps = currentFps.load(std::memory_order_relaxed);
// Validate ranges -- don't send corrupt data to MIDI devices
int maxFrames = frameRateToInt(fps);
if (tc.hours > 23 || tc.minutes > 59 || tc.seconds > 59 || tc.frames >= maxFrames)
return;
int rateCode = fpsToRateCode(fps);
uint8_t hr = (uint8_t)((tc.hours & 0x1F) | (rateCode << 5));
uint8_t sysex[] = {
0xF0, 0x7F, 0x7F, 0x01, 0x01,
hr,
(uint8_t)tc.minutes,
(uint8_t)tc.seconds,
(uint8_t)tc.frames,
0xF7
};
midiOutput->sendMessageNow(juce::MidiMessage(sysex, sizeof(sysex)));
}
private:
//==============================================================================
// Runs on HighResolutionTimer thread (~1ms precision)
void hiResTimerCallback() override
{
if (midiOutput == nullptr
|| paused.load(std::memory_order_relaxed))
{
stopTimer(); // Don't spin at 1000Hz when there's nothing to send
return;
}
// Single atomic read -- guarantees QF interval and rate code are consistent
FrameRate fps = currentFps.load(std::memory_order_relaxed);
// Fractional accumulator: compare real elapsed time against ideal QF interval
// to eliminate drift caused by integer-ms timer resolution
double now = juce::Time::getMillisecondCounterHiRes();
// MTC is a digital protocol -- always send QFs at nominal frame rate.
// The timecode VALUES advance slower at low pitch (PLL handles that),
// which produces repeated frames. This is correct and keeps receivers
// in sync. Scaling the interval caused MA3 to lose lock at low pitch.
double qfInterval = 1000.0 / (frameRateToDouble(fps) * 4.0);
// Guard against sending too many QFs if the timer fires in a burst
// (allow up to 2 catch-up QFs per callback to handle jitter)
int sent = 0;
double lastSend = lastQfSendTime.load(std::memory_order_relaxed);
while ((now - lastSend) >= qfInterval && sent < 2)
{
// At QF index 0, determine the timecode for this entire 8-QF cycle.
// Auto-increment: advance by 2 frames (one QF cycle = 2 frame durations).
// Compare with pendingTimecode and only resync on diff > 2 (seek/jump).
// This prevents 1-frame backward jitter from interpolation overshoot
// causing a full QF cycle of wrong data → MTC receiver flicker.
// Same architectural pattern as the LTC encoder's auto-increment.
int qfIdx = currentQFIndex.load(std::memory_order_relaxed);
if (qfIdx == 0)
{
Timecode pending;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
pending = pendingTimecode;
}
if (!mtcSeeded)
{
cycleTimecode = pending;
mtcSeeded = true;
}
else
{
// Auto-increment by 2 frames (1 QF cycle = 2 frame durations)
cycleTimecode = incrementFrame(incrementFrame(cycleTimecode, fps), fps);
// Resync if pending differs by more than 2 frames (seek/jump)
int maxFrames = frameRateToInt(fps);
auto toTotal = [maxFrames](const Timecode& t) -> int64_t {
return (int64_t)t.hours * 3600 * maxFrames
+ (int64_t)t.minutes * 60 * maxFrames
+ (int64_t)t.seconds * maxFrames
+ (int64_t)t.frames;
};
int64_t dayFrames = (int64_t)24 * 3600 * maxFrames;
int64_t rawDiff = toTotal(pending) - toTotal(cycleTimecode);
int64_t diff = ((rawDiff % dayFrames) + dayFrames) % dayFrames;
if (diff > dayFrames / 2) diff = dayFrames - diff;
if (diff > 2)
cycleTimecode = pending;
}
}
sendQuarterFrame(qfIdx, fps);
qfIdx++;
if (qfIdx >= 8)
qfIdx = 0;
currentQFIndex.store(qfIdx, std::memory_order_relaxed);
// Advance by ideal interval (not by 'now') to prevent cumulative drift
lastSend += qfInterval;
sent++;
}
lastQfSendTime.store(lastSend, std::memory_order_relaxed);
// If we fell too far behind (>50ms), reset to avoid a burst of catch-up sends
if ((now - lastSend) > 50.0)
lastQfSendTime.store(now, std::memory_order_relaxed);
}
void sendQuarterFrame(int index, FrameRate fps)
{
// MTC spec: QF messages encode the timecode that was current
// at the START of the 8-QF sequence (2 frames ago from receiver's perspective)
// The receiver compensates internally.
int value = 0;
switch (index)
{
case 0: value = cycleTimecode.frames & 0x0F; break;
case 1: value = (cycleTimecode.frames >> 4) & 0x01; break;
case 2: value = cycleTimecode.seconds & 0x0F; break;
case 3: value = (cycleTimecode.seconds >> 4) & 0x03; break;
case 4: value = cycleTimecode.minutes & 0x0F; break;
case 5: value = (cycleTimecode.minutes >> 4) & 0x03; break;
case 6: value = cycleTimecode.hours & 0x0F; break;
case 7:
{
int rateCode = fpsToRateCode(fps);
value = ((cycleTimecode.hours >> 4) & 0x01) | (rateCode << 1);
break;
}
}
uint8_t dataByte = (uint8_t)((index << 4) | (value & 0x0F));
midiOutput->sendMessageNow(juce::MidiMessage(0xF1, (int)dataByte));
}
void updateTimerRate()
{
// Run timer at 1ms fixed rate -- the fractional accumulator in
// hiResTimerCallback handles exact QF timing to avoid drift
lastQfSendTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
startTimer(1);
}
//==============================================================================
std::unique_ptr<juce::MidiOutput> midiOutput;
juce::Array<juce::MidiDeviceInfo> availableDevices;
int currentDeviceIndex = -1;
std::atomic<bool> isRunningFlag { false };
std::atomic<bool> paused { false };
juce::SpinLock tcLock;
Timecode pendingTimecode; // Written by UI thread, read under tcLock
Timecode cycleTimecode; // Timer-thread-only: snapshot taken at QF index 0, read through QF 1-7
bool mtcSeeded = false; // Auto-increment: false until first QF0 seeds cycleTimecode
std::atomic<FrameRate> currentFps { FrameRate::FPS_25 };
// currentQFIndex is primarily accessed from the timer thread, but reset from
// the UI thread in start()/setPaused() after stopTimer(). JUCE guarantees
// stopTimer() blocks until the current callback completes, but we use atomic
// as belt-and-suspenders safety against platform-specific timing.
std::atomic<int> currentQFIndex { 0 };
std::atomic<double> lastQfSendTime { 0.0 };
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MtcOutput)
};