Repository navigation
Expand file tree
/
Copy pathMtcInput.h
More file actions
670 lines (601 loc) · 31.2 KB
/
Copy pathMtcInput.h
File metadata and controls
670 lines (601 loc) · 31.2 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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
// 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() stops the device, so nothing calls this object once it
// returns. The retired devices are then destroyed with the members,
// at once: there is no later tick to defer them to (see stop()).
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)
{
// Clear the decoder BEFORE the device delivers anything. A
// MidiInput calls back only between its start() and stop() (JUCE
// drops what arrives while it is not started), and the previous
// device was stopped by stop() above, so nothing runs
// handleIncomingMidiMessage while resetState() writes the
// MIDI-thread state; the release store and the device's start()
// publish it to the MIDI thread.
resetState();
midiInput = std::move(device);
currentDeviceIndex = deviceIndex;
isRunningFlag.store(true, std::memory_order_release);
midiInput->start();
return true;
}
return false;
}
void stop()
{
isRunningFlag.store(false, std::memory_order_release);
if (midiInput != nullptr)
{
// Stop the device, then retire it -- do NOT destroy it here.
//
// Stopping is safe and is what makes a restart clean: in JUCE 9,
// MidiInput::stop() only clears the input's "active" flag under
// the spin lock its dispatcher holds (try-lock) while it calls us,
// so when it returns no callback from this device is in flight and
// none will start. Without it a retired device kept delivering
// into this object until it was destroyed, and a start() right
// after (a device change) set isRunningFlag again and let those
// messages in, from another device and possibly another thread,
// while resetState() and the new device's messages ran.
//
// Destroying is what crashed on macOS (1.8.0): CoreMIDI's
// MIDIPortDisconnectSource does not wait for an in-flight read
// callback, and the platform MIDI thread could still be inside
// JUCE's UMP dispatcher. So the device goes to a retirement list
// and is destroyed by drainRetiredDevices() on a later tick.
midiInput->stop();
retiredDevices.push_back(std::move(midiInput));
}
currentDeviceIndex = -1;
}
/// Call periodically from the message thread (the engine's tick, 60 Hz)
/// to destroy the MidiInput devices retired by stop(). They are already
/// stopped; deferring their destruction to the next tick gives an
/// in-flight platform MIDI callback time to return. The next tick
/// normally comes within ~16 ms of stop() (a 60 Hz juce::Timer); it can
/// come much sooner, since stop() runs from UI handlers between ticks,
/// or later if the message thread is busy.
void drainRetiredDevices()
{
if (!retiredDevices.empty())
retiredDevices.clear();
}
bool getIsRunning() const { return isRunningFlag.load(std::memory_order_relaxed); }
//==============================================================================
/// Freewheel (AUDIT D10): how long after the last quarter frame the
/// source still counts as present. A Full Frame does not refresh it: it
/// keeps the source present for two frames at most, and only in the
/// cases presentAt() and the Full Frame handler describe (AUDIT LTC-13).
/// 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); }
/// True while the source counts as present: a quarter frame arrived
/// within the freewheel window -- or, after a Full Frame, as presentAt()
/// says (AUDIT LTC-13).
bool isReceiving() const
{
if (!synced.load(std::memory_order_acquire))
return false;
bool locate;
double locateUntil;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
locate = syncIsLocate;
locateUntil = locatePresentUntilMs;
}
return presentAt(juce::Time::getMillisecondCounterHiRes(), locate, locateUntil);
}
/// Wall-clock instant (hi-res ms counter) of the current sync point: for
/// a quarter-frame sequence, the start of the frame it stands for (a
/// quarter frame after piece 7 arrived, see reconstructAndSync); for a
/// Full Frame, its arrival. 0 if nothing has been decoded yet. The
/// engine no longer uses it (it takes value and phase together from
/// getCurrentTimecode(nowMs, phase), DESIGN D29).
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 (DESIGN 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.
///
/// A Full Frame is a locate (AUDIT LTC-13). Received while the source
/// is absent -- a sender locating while stopped -- it does not make it
/// present: the value stays frozen on the located frame until the
/// stream gives a whole value that runs, which is the first complete
/// quarter-frame sequence, or a Full Frame that continues the stream in
/// time (continuesStream). Quarter frames before that change nothing:
/// one piece carries four bits of the value at most, too few to tell the
/// located frame from a stale one. So after a locate while stopped the
/// outputs start with the sender's first complete sequence, 1.75 frames
/// after it starts playing and at the position it has reached by then,
/// as they do for a stream that starts without a Full Frame. Received
/// while the source is present, a Full Frame runs from its arrival like
/// any sync point, but keeps the source present for two frames only
/// unless quarter frames follow (presentAt). Taken as a source, a
/// locate while stopped counted up through the freewheel window and
/// jumped back when it closed, and a locate followed by play jumped
/// ahead by the time the transport had been parked.
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;
bool locate;
double locateUntil;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
syncTc = lastSyncTimecode;
syncMs = syncTimeMs;
fps = detectedFps;
locate = syncIsLocate;
locateUntil = locatePresentUntilMs;
}
// Presence from the same snapshot and the same clock reading: the
// quarter frame that ends a locate moves the sync point and clears
// the locate in one go.
if (!presentAt(nowMs, locate, locateUntil))
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: stop() clears the flag before it stops the device, so a
// message already being dispatched in between is ignored.
if (!isRunningFlag.load(std::memory_order_acquire)) return;
auto rawData = message.getRawData();
int rawSize = message.getRawDataSize();
if (rawSize >= 2 && rawData[0] == 0xF1)
{
const double now = juce::Time::getMillisecondCounterHiRes();
lastQfReceiveTime.store(now, 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);
// A quarter frame after a Full Frame ends the locate only within
// its grace (endLocateWithinGrace); otherwise the first complete
// sequence ends it, in reconstructAndSync. (syncIsLocate is
// written only on this thread while a device is started, so this
// thread reads it without the lock.)
if (syncIsLocate)
endLocateWithinGrace(now);
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
{
int hr = sysex[4];
int mn = sysex[5];
int sc = sysex[6];
int fr = sysex[7];
int rateCode = (hr >> 5) & 0x03;
hr &= 0x1F;
// The quarter-frame path's range sanity, frames checked
// against the rate this message names (24, 25, 29.97, 30): a
// malformed Full Frame must not become the sync point. Plus
// one check the quarter-frame path does not make: at 29.97
// drop-frame, frames 00 and 01 do not exist at second 00 of
// a minute that is not a multiple of ten, so such an address
// is rejected here.
static constexpr int kFramesPerRateCode[4] = { 24, 25, 30, 30 };
if (hr > 23 || mn > 59 || sc > 59 || fr >= kFramesPerRateCode[rateCode])
return;
if (rateCode == 2 && sc == 0 && fr < 2 && mn % 10 != 0)
return;
// A Full Frame message is an explicit locate (AUDIT LTC-13).
// It is not a quarter frame: it does not refresh
// lastQfReceiveTime, and while it is the sync point
// (syncIsLocate) the source is present only until
// locatePresentUntilMs.
//
// Received while the source is present, it runs from here
// like any sync point for kLocateGraceFrames, or the
// freewheel if shorter: a sender playing through it resumes
// the quarter frames in that time, and one that has stopped
// and located stops the outputs at the located frame instead
// of freewheeling past it.
//
// Received while the source is absent -- a locate while
// stopped, or a sender's stale opening Full Frame -- it gets
// no grace unless it continues the stream (continuesStream):
// the value stays frozen on it and the outputs paused until
// the stream gives a whole value that runs, which is the
// first complete quarter-frame sequence (reconstructAndSync)
// or a Full Frame that continues this one.
const double now = juce::Time::getMillisecondCounterHiRes();
const bool wasPresent = isReceiving();
{
const juce::SpinLock::ScopedLockType lock(tcLock);
const FrameRate previousFps = detectedFps;
updateDetectedFps(rateCode);
Timecode located;
located.hours = hr;
located.minutes = mn;
located.seconds = sc;
located.frames = fr;
const bool continues = !wasPresent && detectedFps == previousFps
&& continuesStream(located, now);
lastSyncTimecode = located;
syncTimeMs = now;
syncIsLocate = true;
locatePresentUntilMs = (wasPresent || continues)
? now + juce::jmin(kLocateGraceFrames * 1000.0 / frameRateToDouble(detectedFps),
timeoutMs.load(std::memory_order_relaxed))
: 0.0;
}
// Drop the quarter-frame continuity anchor so the next
// assembled sequence is accepted at face value wherever it
// lands. The pieces gathered so far are dropped with it.
continuityValid = false;
pendingValid = false;
nibbleMask = 0;
synced.store(true, std::memory_order_release);
}
}
}
private:
/// How long a Full Frame keeps a present source present without quarter
/// frames. Pico-Timecode sends Full Frames during play and resumes the
/// quarter frames 1.14-1.17 frames later (the #16 captures, BENCH B5);
/// two frames leave room for that and for MIDI jitter. It is also the
/// longest silence (plus a quarter frame) after which a Full Frame can
/// still continue the stream (continuesStream).
static constexpr double kLocateGraceFrames = 2.0;
/// Whether the source is present at `now`. While a Full Frame is the
/// sync point (`locate`), until `locateUntil` -- never, if it came while
/// the source was absent and did not continue the stream
/// (continuesStream, AUDIT LTC-13). Otherwise, while the last quarter
/// frame is within the freewheel window.
bool presentAt(double now, bool locate, double locateUntil) const
{
if (locate)
return now < locateUntil;
// MTC at 24fps sends QF every ~10.4ms, at 30fps ~8.3ms
return now - lastQfReceiveTime.load(std::memory_order_relaxed)
< timeoutMs.load(std::memory_order_relaxed);
}
/// MIDI thread, under tcLock, before a Full Frame naming `located`
/// replaces the sync point while the source is absent: whether it
/// continues the stream that sync point (a sequence, or an earlier Full
/// Frame) stands for, so that it runs with the grace a present source
/// gives it. It does when it names the frame that sync point has run
/// to by `nowMs`, within a quarter frame and at least one frame on, and
/// the stream has been silent for at most kLocateGraceFrames (plus that
/// quarter frame) since the last quarter frame or that earlier Full
/// Frame. Two whole values that a running transport links are that
/// transport, not a stale value; a stale Full Frame does not continue
/// what came before it, and waits for a complete sequence like any
/// other. It covers:
/// - Pico-Timecode's start at 29.97 and 30 fps, pairs "Full Frame N,
/// piece 0 of N+1" two frames apart for 0.25-0.7 s (the #16 captures):
/// the second Full Frame continues the first;
/// - a freewheel shorter than the sender's own gap before a Full Frame
/// it sends during play (Pico-Timecode's 52-60 ms against 50 ms): the
/// Full Frame continues the last sequence.
/// A Full-Frame-only shuttle or wind from stop does not continue it
/// (its frames move faster or slower than the clock), nor does a
/// sender that sends the same locate again.
bool continuesStream(const Timecode& located, double nowMs) const
{
const double msPerFrame = 1000.0 / frameRateToDouble(detectedFps);
const double lastHeard = syncIsLocate
? juce::jmax(syncTimeMs, lastQfReceiveTime.load(std::memory_order_relaxed))
: lastQfReceiveTime.load(std::memory_order_relaxed);
if (!synced.load(std::memory_order_relaxed)
|| nowMs - lastHeard > (kLocateGraceFrames + 0.25) * msPerFrame)
return false;
const int64_t advance = timecodeToFrameIndex(located, detectedFps)
- timecodeToFrameIndex(lastSyncTimecode, detectedFps);
const double ran = (nowMs - syncTimeMs) / msPerFrame;
return advance >= 1 && std::abs((double) advance - ran) <= 0.25;
}
/// MIDI thread: a quarter frame while a Full Frame is the sync point.
/// Within the Full Frame's grace, the sender played on through it: its
/// value has been running since it arrived, and presence is the quarter
/// frames' again (Pico-Timecode resumes with piece 0 of the next frame
/// 1.14-1.17 frames after a Full Frame it sends during play).
///
/// After the grace -- always, for a Full Frame that came while the
/// source was absent and did not continue the stream -- nothing
/// changes: the locate holds, frozen and absent, until the first
/// complete sequence ends it in reconstructAndSync (1.75 frames after
/// the sender's first piece, if that is a piece 0; up to a sequence
/// later otherwise), or a Full Frame continues it (continuesStream). A
/// single piece carries four bits of the value at most, and cannot tell
/// a transport that starts at the located frame from a stale Full Frame
/// followed by a stream elsewhere (Pico-Timecode opens mtc_25fps_even
/// with a Full Frame of 00:59:30:09 and then streams 00:59:33:20; a
/// stream at 33:09, 33:10 or 33:11 would have carried the low nibble of
/// one of the located frame and the next two in its first piece 0).
void endLocateWithinGrace(double nowMs)
{
const juce::SpinLock::ScopedLockType lock(tcLock);
if (nowMs < locatePresentUntilMs)
syncIsLocate = false;
}
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, and the interpolation in
// getCurrentTimecode, assume forward playback. Reverse play is
// not decoded as such (BENCH B7, AUDIT LTC-20): the quarter frames
// come 7..0, a sequence completes when the next piece 7 arrives,
// and its value is two frames LOWER than the last one -- inside
// the continuity tolerance, so it is accepted -- then gets +2 here
// and runs forward from its sync point. For as long as reverse
// play lasts the published value is a sawtooth going backwards:
// two frames forward, four back, every sequence.
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);
// A complete sequence ends a locate that no quarter frame ended
// within its grace (endLocateWithinGrace): presence is the
// freewheel window's again.
syncIsLocate = false;
}
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:
// Rate code 0 is 24 fps. MTC has no code for 23.976 -- a
// 23.976 sender uses 0 too -- so this reports 24 and cannot
// tell the two apart. Keeping a 23.976 the user selected is
// the engine's job (as userOverrodeLtcFps does for LTC), not
// the decoder's: nothing here knows the selection (AUDIT NET-4).
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();
syncIsLocate = false;
locatePresentUntilMs = 0.0;
}
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 (AUDIT D10)
// Quarter-frame accumulator -- MIDI-callback-thread-only (resetState()
// writes it on the message thread, but only while no device is started)
int mtcData[8] = {};
uint8_t nibbleMask = 0; // which pieces arrived since the last reconstruction
// Quarter-frame continuity state -- MIDI-callback-thread-only, as above.
// 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;
bool syncIsLocate = false; // the sync point is a Full Frame not yet ended by a quarter frame within its grace or by a sequence
double locatePresentUntilMs = 0.0; // while syncIsLocate: present until then (0: absent)
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)
};