-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathMtcInput.h
More file actions
463 lines (401 loc) · 18.8 KB
/
Copy pathMtcInput.h
File metadata and controls
463 lines (401 loc) · 18.8 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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// 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 MtcInput : public juce::MidiInputCallback
{
public:
MtcInput() = default;
~MtcInput() 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::MidiInput::getAvailableDevices();
}
//==============================================================================
bool start(int deviceIndex)
{
stop();
if (deviceIndex < 0 || deviceIndex >= availableDevices.size())
return false;
auto device = juce::MidiInput::openDevice(availableDevices[deviceIndex].identifier, this);
if (device != nullptr)
{
midiInput = std::move(device);
midiInput->start();
currentDeviceIndex = deviceIndex;
isRunningFlag.store(true, std::memory_order_relaxed);
resetState();
return true;
}
return false;
}
void stop()
{
isRunningFlag.store(false, std::memory_order_release);
if (midiInput != nullptr)
{
// Do NOT call midiInput->stop() or destroy it here. On macOS,
// CoreMIDI's MIDI thread may be mid-callback inside JUCE's UMP
// dispatcher. Both stop() and ~MidiInput() can deadlock or crash.
//
// Move the device to a retirement list. It stays alive until
// drainRetiredDevices() is called from the message thread timer
// (16ms later), by which time any in-flight callback has returned.
retiredDevices.push_back(std::move(midiInput));
}
currentDeviceIndex = -1;
}
/// Call periodically from the message thread (e.g. timerCallback at 60Hz)
/// to safely destroy MidiInput devices that were retired by stop().
/// By the time this runs (~16ms after stop()), CoreMIDI callbacks have
/// finished and the destructors are safe to call.
void drainRetiredDevices()
{
if (!retiredDevices.empty())
retiredDevices.clear();
}
bool getIsRunning() const { return isRunningFlag.load(std::memory_order_relaxed); }
//==============================================================================
// True if QF messages are actively arriving
/// Freewheel (D10): how long after the last frame/packet the source still
/// counts as present. The senders count on their own through it, so a
/// short dropout -- a USB stall, a display wake -- never reaches the
/// wire; the price is that a real stop takes this long to reach the
/// outputs. The operator sets it (engine setting), default
/// kSourceTimeoutMs.
void setTimeoutMs(double ms) { timeoutMs.store(juce::jmax(50.0, ms), std::memory_order_relaxed); }
double getTimeoutMs() const { return timeoutMs.load(std::memory_order_relaxed); }
bool isReceiving() const
{
if (!synced.load(std::memory_order_acquire))
return false;
double now = juce::Time::getMillisecondCounterHiRes();
double elapsed = now - lastQfReceiveTime.load(std::memory_order_relaxed);
// MTC at 24fps sends QF every ~10.4ms, at 30fps ~8.3ms
return elapsed < timeoutMs.load(std::memory_order_relaxed);
}
/// Wall-clock instant (hi-res ms counter) at which the last complete
/// timecode was reconstructed. MTC is a frame-based source, so this is
/// the frame boundary as far as the rest of STC is concerned -- and it is
/// far more precise than watching the value change from the 60Hz tick.
/// 0 if nothing has been decoded yet.
double getLastFrameArrivalMs() const
{
const juce::SpinLock::ScopedLockType lock(tcLock);
return syncTimeMs;
}
Timecode getCurrentTimecode() const
{
double phaseIgnored = 0.0;
return getCurrentTimecode(juce::Time::getMillisecondCounterHiRes(), phaseIgnored);
}
/// The live value at `nowMs`, and how far into that frame the source is
/// (`phaseMsOut`, 0 .. one frame). Both come from ONE elapsed against ONE
/// sync point, read under one lock -- that is the whole point of this
/// overload (D29, issue #22).
///
/// The sync point is dated a quarter frame into the future on purpose
/// (piece 7 arrives at N + 1.75 frames; the value N + 2 begins a quarter
/// frame later), so for the first 10 ms after every sequence `elapsed` is
/// NEGATIVE. The old code returned the sync value outright for a negative
/// elapsed, while the engine took the phase with an fmod and wrapped the
/// negative remainder up by a frame: value N + 2, phase 30 ms, when the
/// truth was N + 1 at 30 ms. A pair one frame high for a quarter frame
/// out of every two, sampled by a 60 Hz tick more often than not, and the
/// LTC encoder's tracking let one through now and then as a skipped frame
/// with a repeat to come back. floor() on the same number gives N + 1 at
/// 30 ms, which is where the stream is.
Timecode getCurrentTimecode(double nowMs, double& phaseMsOut) const
{
phaseMsOut = 0.0;
if (!synced.load(std::memory_order_acquire))
return Timecode();
Timecode syncTc;
double syncMs;
FrameRate fps;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
syncTc = lastSyncTimecode;
syncMs = syncTimeMs;
fps = detectedFps;
}
if (!isReceiving())
return syncTc; // frozen: the last value, no phase to speak of
const double msPerFrame = 1000.0 / frameRateToDouble(fps);
const double elapsed = nowMs - syncMs;
// Interpolate from the last sync point on the drop-frame-aware frame
// index, so landing across a 59;29 -> 00;02 crossing yields the next
// valid address instead of a patched one. floor(), not truncation:
// a negative elapsed is the frame BEFORE the sync value, part-way
// through, and the remainder must say so.
const double whole = std::floor(elapsed / msPerFrame);
phaseMsOut = elapsed - whole * msPerFrame;
return frameIndexToTimecode(timecodeToFrameIndex(syncTc, fps) + (int64_t) whole, fps);
}
FrameRate getDetectedFrameRate() const
{
const juce::SpinLock::ScopedLockType lock(tcLock);
return detectedFps;
}
//==============================================================================
void handleIncomingMidiMessage(juce::MidiInput*, const juce::MidiMessage& message) override
{
// Guard: after stop(), the device may still deliver a queued message
// before CoreMIDI fully disconnects. Ignore it.
if (!isRunningFlag.load(std::memory_order_acquire)) return;
auto rawData = message.getRawData();
int rawSize = message.getRawDataSize();
if (rawSize >= 2 && rawData[0] == 0xF1)
{
lastQfReceiveTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
int dataByte = rawData[1];
int index = (dataByte >> 4) & 0x07; // 0-7 guaranteed by mask
int value = dataByte & 0x0F;
mtcData[index] = value;
nibbleMask |= (uint8_t)(1 << index);
if (index == 7)
reconstructAndSync();
}
else if (message.isSysEx())
{
auto* sysex = message.getSysExData();
int sysexSize = message.getSysExDataSize();
if (sysexSize >= 8 &&
sysex[0] == 0x7F && // Universal Real Time
// sysex[1] = device ID (0x00-0x7F, accept any)
sysex[2] == 0x01 && sysex[3] == 0x01) // MTC Full Frame
{
lastQfReceiveTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
int hr = sysex[4];
int mn = sysex[5];
int sc = sysex[6];
int fr = sysex[7];
int rateCode = (hr >> 5) & 0x03;
hr &= 0x1F;
// Same range sanity as the quarter-frame path: a malformed
// Full Frame must not become the sync point.
if (hr > 23 || mn > 59 || sc > 59 || fr > 29)
return;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
updateDetectedFps(rateCode);
lastSyncTimecode.hours = hr;
lastSyncTimecode.minutes = mn;
lastSyncTimecode.seconds = sc;
lastSyncTimecode.frames = fr;
syncTimeMs = juce::Time::getMillisecondCounterHiRes();
}
// A Full Frame message is an explicit locate: drop the
// quarter-frame continuity anchor so the next assembled
// sequence is accepted at face value wherever it lands.
continuityValid = false;
pendingValid = false;
nibbleMask = 0;
synced.store(true, std::memory_order_release);
}
}
}
private:
void reconstructAndSync()
{
// --- Sequence integrity ---
// Reconstruct only when all eight nibbles have arrived since the
// last reconstruction. Without this, a dropped or delayed quarter
// frame silently mixes stale nibbles into the assembled value.
// On failure keep accumulating (do NOT clear): the mask completes
// naturally once a full sequence has passed through.
if (nibbleMask != 0xFF)
return;
nibbleMask = 0;
Timecode assembled;
assembled.frames = mtcData[0] | (mtcData[1] << 4);
assembled.seconds = mtcData[2] | (mtcData[3] << 4);
assembled.minutes = mtcData[4] | (mtcData[5] << 4);
assembled.hours = mtcData[6] | ((mtcData[7] & 0x01) << 4);
int rateCode = (mtcData[7] >> 1) & 0x03;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
updateDetectedFps(rateCode);
const int maxFrames = frameRateToInt(detectedFps);
// Range sanity: a malformed sequence is dropped outright rather
// than propagated as a position.
if (assembled.frames >= maxFrames || assembled.frames < 0
|| assembled.seconds > 59 || assembled.seconds < 0
|| assembled.minutes > 59 || assembled.minutes < 0
|| assembled.hours > 23 || assembled.hours < 0)
{
continuityValid = false;
return;
}
// --- Continuity guard (issue #16) ---
// The eight quarter frames of one sequence span two frame
// periods. Some generators latch the timecode at the first
// quarter frame and send the nibbles of that single value;
// others emit each nibble from the live counter. With the
// latter, a sequence that straddles a second boundary carries
// its low-order nibbles (frames, seconds -- sent first) from
// before the boundary and its high-order nibbles (minutes,
// hours) from after it, so the assembled value is a splice of
// two different times.
//
// At 30fps this only happens when the first quarter frame falls
// on an ODD frame: 30 is even, so even-aligned sequences pair
// as (0,1)(2,3)...(28,29) and never cross a second boundary,
// while odd-aligned ones pair as (1,2)...(29,0) and cross once
// per second. Once per minute that crossing is also a minute
// rollover, and the splice reads e.g. minutes=01 with
// seconds=59 -- roughly a minute out, for one sequence, which
// is the reported glitch. 25fps alternates alignment every
// second because 25 is odd, so it depends on generator phase.
//
// Consecutive sequences are two frames apart, so any assembled
// value that is not within tolerance of the previous one plus
// two frames is treated as suspect and replaced by the
// continuity-derived value. A genuine jump (a locate that
// arrives without a Full Frame message) repeats consistently,
// so a suspect value confirmed by the next sequence is accepted
// -- costing at most one extra sequence of latency on a
// quarter-frame-only locate.
// Distances are measured on the drop-frame-aware frame index, so
// a 29.97DF minute rollover reads as the two-frame advance it is.
static constexpr int64_t kToleranceFrames = 4;
if (continuityValid)
{
const Timecode expected = advanceTwoFrames(prevAssembled, detectedFps);
const int64_t delta = frameDistance(assembled, expected, detectedFps);
if (delta > kToleranceFrames || delta < -kToleranceFrames)
{
bool confirmed = false;
if (pendingValid)
{
const Timecode pexp = advanceTwoFrames(pendingAssembled, detectedFps);
const int64_t pdelta = frameDistance(assembled, pexp, detectedFps);
confirmed = (pdelta <= kToleranceFrames && pdelta >= -kToleranceFrames);
}
if (!confirmed)
{
// Reject this sequence: hold the timeline together
// with the continuity-derived value and remember
// the rejected one in case the next sequence
// confirms it as a real jump.
pendingAssembled = assembled;
pendingValid = true;
assembled = expected;
}
else
{
pendingValid = false;
}
}
else
{
pendingValid = false;
}
}
prevAssembled = assembled;
continuityValid = true;
// MTC quarter-frame messages describe the timecode from 2 frames
// prior (8 QFs x 1/4 frame = 2 frames of latency). Advancing by
// two compensates so the reported position matches the present.
// Uses incrementFrame so 29.97 drop-frame skips are honoured --
// linear arithmetic here used to emit frames 00/01 of a
// non-tenth minute, which do not exist in drop-frame numbering.
// NOTE: this compensation assumes forward playback. Reverse
// operations may briefly show a +/-4 frame discrepancy until the
// next full 8-QF cycle completes.
lastSyncTimecode = advanceTwoFrames(assembled, detectedFps);
// Piece 7 is sent at the start of the last quarter of the second
// frame, so it arrives at N + 1.75 frames; the value N + 2 above
// begins a quarter frame later. The sync instant is that start,
// so the phase published to the LTC encoder is not a quarter
// frame early.
syncTimeMs = juce::Time::getMillisecondCounterHiRes()
+ 0.25 * 1000.0 / frameRateToDouble(detectedFps);
}
synced.store(true, std::memory_order_release);
}
static Timecode advanceTwoFrames(const Timecode& tc, FrameRate fps)
{
return incrementFrame(incrementFrame(tc, fps), fps);
}
void updateDetectedFps(int rateCode)
{
switch (rateCode)
{
case 0:
// MTC rate code 0 means "24fps". SMPTE MTC has no code for
// 23.976, so if the user has selected FPS_2398 we preserve
// it rather than silently overwriting with FPS_24.
if (detectedFps != FrameRate::FPS_2398)
detectedFps = FrameRate::FPS_24;
break;
case 1: detectedFps = FrameRate::FPS_25; break;
case 2: detectedFps = FrameRate::FPS_2997; break;
case 3: detectedFps = FrameRate::FPS_30; break;
default: break; // Unknown rate code: keep previous value
}
}
void resetState()
{
for (int i = 0; i < 8; i++)
mtcData[i] = 0;
nibbleMask = 0;
continuityValid = false;
pendingValid = false;
prevAssembled = Timecode();
pendingAssembled = Timecode();
synced.store(false, std::memory_order_relaxed);
{
const juce::SpinLock::ScopedLockType lock(tcLock);
syncTimeMs = 0.0;
lastSyncTimecode = Timecode();
}
lastQfReceiveTime.store(0.0, std::memory_order_relaxed);
}
std::unique_ptr<juce::MidiInput> midiInput;
std::vector<std::unique_ptr<juce::MidiInput>> retiredDevices; // deferred destruction (see stop())
juce::Array<juce::MidiDeviceInfo> availableDevices;
int currentDeviceIndex = -1;
std::atomic<bool> isRunningFlag { false };
std::atomic<double> timeoutMs { kSourceTimeoutMs }; // freewheel window (D10)
// Quarter-frame accumulator -- MIDI-callback-thread-only
int mtcData[8] = {};
uint8_t nibbleMask = 0; // which pieces arrived since the last reconstruction
// Quarter-frame continuity state -- MIDI-callback-thread-only.
// prevAssembled is the piece-0-time value of the last accepted sequence;
// pendingAssembled holds a rejected value awaiting confirmation.
Timecode prevAssembled;
Timecode pendingAssembled;
bool continuityValid = false;
bool pendingValid = false;
// Protected by tcLock (written from MIDI thread, read from UI thread)
mutable juce::SpinLock tcLock;
Timecode lastSyncTimecode;
double syncTimeMs = 0.0;
FrameRate detectedFps = FrameRate::FPS_25;
// Atomic cross-thread fields
std::atomic<double> lastQfReceiveTime { 0.0 };
std::atomic<bool> synced { false };
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MtcInput)
};