-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLtcOutput.h
More file actions
392 lines (336 loc) · 15.6 KB
/
LtcOutput.h
File metadata and controls
392 lines (336 loc) · 15.6 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
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
#pragma once
#include <JuceHeader.h>
#include "TimecodeCore.h"
#include <atomic>
#include <cmath>
#include <cstdlib>
#include <cstring>
class LtcOutput : private juce::AudioIODeviceCallback
{
public:
LtcOutput() = default;
~LtcOutput() { stop(); }
//==============================================================================
// channel: 0+ = specific channel, -1 = Ch 1 + Ch 2
// sampleRate: preferred sample rate (0 = device default)
// bufferSize: preferred buffer size (0 = device default)
//==============================================================================
bool start(const juce::String& typeName, const juce::String& devName,
int channel = 0, double sampleRate = 0, int bufferSize = 0)
{
stop();
selectedChannel.store(channel, std::memory_order_relaxed);
currentDeviceName = devName;
currentTypeName = typeName;
deviceManager.closeAudioDevice();
// Register all device types without opening anything
deviceManager.initialise(0, 128, nullptr, false);
// Switch to requested type WITHOUT auto-opening a device (false)
if (typeName.isNotEmpty())
deviceManager.setCurrentAudioDeviceType(typeName, false);
// Scan so the device name is recognised
if (auto* type = deviceManager.getCurrentDeviceTypeObject())
type->scanForDevices();
// Open the specific device -- this is the ONLY open call
auto setup = deviceManager.getAudioDeviceSetup();
setup.outputDeviceName = devName;
setup.inputDeviceName = "";
setup.useDefaultInputChannels = false;
setup.useDefaultOutputChannels = true;
if (sampleRate > 0) setup.sampleRate = sampleRate;
if (bufferSize > 0) setup.bufferSize = bufferSize;
auto err = deviceManager.setAudioDeviceSetup(setup, true);
if (err.isNotEmpty())
return false;
auto* device = deviceManager.getCurrentAudioDevice();
if (!device)
return false;
numChannelsAvailable = device->getActiveOutputChannels().countNumberOfSetBits();
{
int ch = selectedChannel.load(std::memory_order_relaxed);
if (ch >= 0 && ch >= numChannelsAvailable)
ch = 0;
if (ch == -1 && numChannelsAvailable < 2)
ch = 0;
selectedChannel.store(ch, std::memory_order_relaxed);
}
currentSampleRate = device->getCurrentSampleRate();
currentBufferSize = device->getCurrentBufferSizeSamples();
resetEncoder();
peakLevel.store(0.0f, std::memory_order_relaxed);
deviceManager.addAudioCallback(this);
isRunningFlag.store(true, std::memory_order_relaxed);
return true;
}
void stop()
{
if (isRunningFlag.load(std::memory_order_relaxed))
{
deviceManager.removeAudioCallback(this);
deviceManager.closeAudioDevice();
isRunningFlag.store(false, std::memory_order_relaxed);
}
}
bool getIsRunning() const { return isRunningFlag.load(std::memory_order_relaxed); }
juce::String getCurrentDeviceName() const { return currentDeviceName; }
juce::String getCurrentTypeName() const { return currentTypeName; }
int getSelectedChannel() const { return selectedChannel.load(std::memory_order_relaxed); }
int getChannelCount() const { return numChannelsAvailable; }
bool isStereoMode() const { return selectedChannel.load(std::memory_order_relaxed) == -1; }
double getActualSampleRate() const { return currentSampleRate; }
int getActualBufferSize() const { return currentBufferSize; }
void setTimecode(const Timecode& tc)
{
packedPendingTc.store(packTimecode(tc.hours, tc.minutes, tc.seconds, tc.frames),
std::memory_order_relaxed);
}
void setFrameRate(FrameRate fps) { pendingFps.store(fps, std::memory_order_relaxed); }
void setPitchMultiplier(double p) { pitchMultiplier.store(p, std::memory_order_relaxed); }
/// Force encoder to re-seed from current pendingTc on next audio callback.
/// Call when resuming from pause to avoid continuing a stale half-encoded frame.
void reseed()
{
needNewFrame.store(true, std::memory_order_relaxed);
encoderSeeded.store(false, std::memory_order_relaxed);
}
void setPaused(bool p)
{
paused.store(p, std::memory_order_relaxed);
if (p)
peakLevel.store(0.0f, std::memory_order_relaxed); // meter drops immediately
}
bool isPaused() const { return paused.load(std::memory_order_relaxed); }
void setOutputGain(float gain) { outputGain.store(juce::jlimit(0.0f, 2.0f, gain), std::memory_order_relaxed); }
float getOutputGain() const { return outputGain.load(std::memory_order_relaxed); }
float getPeakLevel() const { return peakLevel.load(std::memory_order_relaxed); }
private:
juce::AudioDeviceManager deviceManager;
juce::String currentDeviceName;
juce::String currentTypeName;
std::atomic<bool> isRunningFlag { false };
// selectedChannel is written in start() (UI thread) and read in
// audioDeviceIOCallbackWithContext() (audio thread). JUCE's
// addAudioCallback provides a happens-before, but atomic makes
// the cross-thread contract explicit.
std::atomic<int> selectedChannel { 0 };
int numChannelsAvailable = 0;
double currentSampleRate = 48000.0;
int currentBufferSize = 512;
std::atomic<uint64_t> packedPendingTc { 0 };
std::atomic<FrameRate> pendingFps { FrameRate::FPS_25 };
std::atomic<bool> paused { false };
std::atomic<float> outputGain { 1.0f };
std::atomic<float> peakLevel { 0.0f };
std::atomic<double> pitchMultiplier { 1.0 };
// LTC encoder state -- mostly audio-callback-thread-only.
// EXCEPTION: needNewFrame and encoderSeeded are also written by reseed()
// from the message thread, so they must be atomic to avoid data races
// (especially on ARM / Apple Silicon where non-atomic cross-thread writes
// can produce torn reads).
static constexpr int LTC_FRAME_BITS = 80;
uint8_t frameBits[LTC_FRAME_BITS] = {};
int currentBitIndex = 0;
int halfCellIndex = 0;
double samplePositionInHalfBit = 0.0;
double samplesPerHalfBit = 0.0;
float currentLevel = 1.0f;
std::atomic<bool> needNewFrame { true };
static constexpr float baseAmplitude = 0.8f;
// Auto-increment state: the encoder maintains its own running timecode
// to avoid repeating frames when the UI thread lags behind the audio clock
Timecode encoderTc;
std::atomic<bool> encoderSeeded { false };
void resetEncoder()
{
currentBitIndex = 0;
halfCellIndex = 0;
samplePositionInHalfBit = 0.0;
currentLevel = 1.0f;
needNewFrame.store(true, std::memory_order_relaxed);
encoderSeeded.store(false, std::memory_order_relaxed);
encoderTc = Timecode();
updateSamplesPerBit();
}
void updateSamplesPerBit()
{
double fps = frameRateToDouble(pendingFps.load(std::memory_order_relaxed));
double pitch = pitchMultiplier.load(std::memory_order_relaxed);
if (pitch <= 0.0) pitch = 1.0;
// Scale bit duration by pitch: faster pitch -> shorter bits -> more frames/sec
samplesPerHalfBit = currentSampleRate / (fps * pitch * LTC_FRAME_BITS * 2.0);
}
void packFrame()
{
FrameRate fps = pendingFps.load(std::memory_order_relaxed);
Timecode pendingTc = unpackTimecode(packedPendingTc.load(std::memory_order_relaxed));
if (!encoderSeeded.load(std::memory_order_relaxed))
{
encoderTc = pendingTc;
encoderSeeded.store(true, std::memory_order_relaxed);
}
else
{
// Auto-increment from the last encoded frame
encoderTc = incrementFrame(encoderTc, fps);
// If the UI-provided timecode differs significantly (>1 frame),
// re-sync to the UI value (handles seeks, source switches, jumps)
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(pendingTc) - toTotal(encoderTc);
// Modular distance: shortest path around the 24h wheel
int64_t diff = ((rawDiff % dayFrames) + dayFrames) % dayFrames;
if (diff > dayFrames / 2) diff = dayFrames - diff;
if (diff > 1)
encoderTc = pendingTc;
}
int frames = encoderTc.frames;
int seconds = encoderTc.seconds;
int minutes = encoderTc.minutes;
int hours = encoderTc.hours;
int frameUnits = frames % 10, frameTens = frames / 10;
int secUnits = seconds % 10, secTens = seconds / 10;
int minUnits = minutes % 10, minTens = minutes / 10;
int hourUnits = hours % 10, hourTens = hours / 10;
bool dropFrame = (fps == FrameRate::FPS_2997);
std::memset(frameBits, 0, LTC_FRAME_BITS);
frameBits[0] = (frameUnits >> 0) & 1;
frameBits[1] = (frameUnits >> 1) & 1;
frameBits[2] = (frameUnits >> 2) & 1;
frameBits[3] = (frameUnits >> 3) & 1;
frameBits[8] = (frameTens >> 0) & 1;
frameBits[9] = (frameTens >> 1) & 1;
frameBits[10] = dropFrame ? 1 : 0;
frameBits[16] = (secUnits >> 0) & 1;
frameBits[17] = (secUnits >> 1) & 1;
frameBits[18] = (secUnits >> 2) & 1;
frameBits[19] = (secUnits >> 3) & 1;
frameBits[24] = (secTens >> 0) & 1;
frameBits[25] = (secTens >> 1) & 1;
frameBits[26] = (secTens >> 2) & 1;
// Biphase polarity correction bit 27 (BGF0):
// even parity over bits 0-26 so total 1s in bits 0-27 is even.
// User bits at positions 4-7, 12-15, 20-23 are within this range
// and ARE correctly included in the sum. User bits group 4 (bits
// 28-31) are outside this parity region and do not participate.
int parityLow = 0;
for (int i = 0; i < 27; i++)
parityLow += frameBits[i];
frameBits[27] = (parityLow & 1) ? 1 : 0;
frameBits[32] = (minUnits >> 0) & 1;
frameBits[33] = (minUnits >> 1) & 1;
frameBits[34] = (minUnits >> 2) & 1;
frameBits[35] = (minUnits >> 3) & 1;
frameBits[40] = (minTens >> 0) & 1;
frameBits[41] = (minTens >> 1) & 1;
frameBits[42] = (minTens >> 2) & 1;
frameBits[48] = (hourUnits >> 0) & 1;
frameBits[49] = (hourUnits >> 1) & 1;
frameBits[50] = (hourUnits >> 2) & 1;
frameBits[51] = (hourUnits >> 3) & 1;
frameBits[56] = (hourTens >> 0) & 1;
frameBits[57] = (hourTens >> 1) & 1;
frameBits[64] = 0; frameBits[65] = 0; frameBits[66] = 1; frameBits[67] = 1;
frameBits[68] = 1; frameBits[69] = 1; frameBits[70] = 1; frameBits[71] = 1;
frameBits[72] = 1; frameBits[73] = 1; frameBits[74] = 1; frameBits[75] = 1;
frameBits[76] = 1; frameBits[77] = 1; frameBits[78] = 0; frameBits[79] = 1;
// Biphase polarity correction bit 59 (BGF2):
// even parity over bits 32-58 so total 1s in bits 32-59 is even.
// User bits at positions 36-39, 44-47, 52-55 are within this range
// and ARE correctly included in the sum. User bits group 8 (bits
// 60-63) are outside this parity region and do not participate.
int parityHigh = 0;
for (int i = 32; i < 59; i++)
parityHigh += frameBits[i];
frameBits[59] = (parityHigh & 1) ? 1 : 0;
}
//==============================================================================
void audioDeviceIOCallbackWithContext(const float* const*, int,
float* const* outputChannelData,
int numOutputChannels, int numSamples,
const juce::AudioIODeviceCallbackContext&) override
{
for (int ch = 0; ch < numOutputChannels; ch++)
if (outputChannelData[ch])
std::memset(outputChannelData[ch], 0, sizeof(float) * (size_t)numSamples);
if (paused.load(std::memory_order_relaxed))
return;
int selCh = selectedChannel.load(std::memory_order_relaxed);
bool stereoMode = (selCh == -1);
int primaryCh = stereoMode ? 0 : selCh;
if (primaryCh >= numOutputChannels || !outputChannelData[primaryCh])
return;
float* output = outputChannelData[primaryCh];
float* output2 = (stereoMode && numOutputChannels >= 2 && outputChannelData[1])
? outputChannelData[1] : nullptr;
const float amplitude = baseAmplitude * outputGain.load(std::memory_order_relaxed);
float peak = 0.0f;
for (int i = 0; i < numSamples; ++i)
{
if (needNewFrame.load(std::memory_order_relaxed))
{
updateSamplesPerBit();
packFrame();
currentBitIndex = 0;
halfCellIndex = 0;
samplePositionInHalfBit = 0.0;
needNewFrame.store(false, std::memory_order_relaxed);
// Do NOT invert currentLevel here -- the mandatory start-of-bit
// transition for bit 0 was already applied when the previous
// frame's last bit completed (halfCellIndex 1 -> 0 branch).
// An extra inversion here would cancel it out, creating a
// biphase parity error.
}
float sample = currentLevel * amplitude;
output[i] = sample;
if (output2) output2[i] = sample;
float a = std::abs(sample);
if (a > peak) peak = a;
samplePositionInHalfBit += 1.0;
if (samplePositionInHalfBit >= samplesPerHalfBit)
{
samplePositionInHalfBit -= samplesPerHalfBit;
if (halfCellIndex == 0)
{
halfCellIndex = 1;
if (frameBits[currentBitIndex] == 1)
currentLevel = -currentLevel;
}
else
{
halfCellIndex = 0;
currentBitIndex++;
// Mandatory biphase-mark transition at start of every
// bit cell -- including bit 0 of the next frame.
currentLevel = -currentLevel;
if (currentBitIndex >= LTC_FRAME_BITS)
needNewFrame.store(true, std::memory_order_relaxed);
}
}
}
peakLevel.store(peak, std::memory_order_relaxed);
}
void audioDeviceAboutToStart(juce::AudioIODevice* device) override
{
if (device)
{
currentSampleRate = device->getCurrentSampleRate();
currentBufferSize = device->getCurrentBufferSizeSamples();
numChannelsAvailable = device->getActiveOutputChannels().countNumberOfSetBits();
}
resetEncoder();
}
void audioDeviceStopped() override
{
peakLevel.store(0.0f, std::memory_order_relaxed);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LtcOutput)
};