Browse Source

WIP rea165-midisync: MIDI clock / MTC master sync, external clock sync, all notes off (core, engine, Settings › MIDI)

Ka1-S 1 month ago
parent
commit
bd5de5e29b

+ 2 - 0
CMakeLists.txt

@@ -51,6 +51,7 @@ add_library(lynx_core STATIC
     src/core/ProjectSafety.cpp
     src/core/PluginSubstitutes.cpp
     src/core/Preferences.cpp
+    src/core/MidiSync.cpp
     src/core/ThemePalette.cpp
     src/core/PluginLayout.cpp
     src/core/StateParams.cpp
@@ -292,6 +293,7 @@ if(LYNX_BUILD_APP)
         src/engine/Vst2Format.cpp
         src/engine/MidiFileIo.cpp
         src/engine/AudioLogger.cpp
+        src/engine/MidiSyncIo.cpp
         src/engine/PreviewPlayer.cpp
         src/ui/MainComponent.cpp
         src/ui/ChannelRackComponent.cpp

+ 29 - 0
resources/i18n/pt-BR.txt

@@ -5193,3 +5193,32 @@ countries: br
 "Thickness" = "Espessura"
 "Beat threshold" = "Limiar da batida"
 "Hue shift" = "Rotação de matiz"
+
+# --- Settings › MIDI: master sync and external clock (round 165f)
+"Output devices" = "Dispositivos de saída"
+"No MIDI output devices found." = "Nenhum dispositivo de saída MIDI encontrado."
+"Send master sync drives drum machines, synths and other software from LYNX's transport: MIDI clock with Song Position Pointer, or MIDI Time Code." = "Enviar sincronização mestre comanda baterias eletrônicas, sintetizadores e outros programas pelo transporte do LYNX: MIDI clock com Song Position Pointer, ou MIDI Time Code."
+"Send master sync" = "Enviar sincronização mestre"
+"Send master synchronization to this device" = "Envia a sincronização mestre para este dispositivo"
+"MIDI clock: 24 pulses per quarter note, Start / Continue / Stop and Song Position Pointer. MTC: MIDI Time Code quarter frames and a full frame when the position moves." = "MIDI clock: 24 pulsos por semínima, Start / Continue / Stop e Song Position Pointer. MTC: quarter frames de MIDI Time Code e um full frame quando a posição muda."
+"MIDI clock" = "MIDI clock"
+"MTC 24 fps" = "MTC 24 fps"
+"MTC 25 fps" = "MTC 25 fps"
+"MTC 30 fps (drop)" = "MTC 30 fps (drop-frame)"
+"MTC 30 fps (non-drop)" = "MTC 30 fps (non-drop)"
+"MTC 29.97 fps (drop)" = "MTC 29,97 fps (drop-frame)"
+"MTC 29.97 fps (non-drop)" = "MTC 29,97 fps (non-drop)"
+"Offset (ms)" = "Deslocamento (ms)"
+"Master sync offset (milliseconds): positive sends the sync later, negative earlier" = "Deslocamento da sincronização mestre (milissegundos): positivo envia mais tarde, negativo mais cedo"
+"Send all notes off" = "Enviar all notes off"
+"Send all notes off to this device on init and after an export" = "Envia all notes off a este dispositivo ao iniciar e depois de uma exportação"
+"External sync" = "Sincronização externa"
+"External clock sync" = "Sincronizar com clock externo"
+"LYNX follows the MIDI clock of this input: its tempo, Start / Continue / Stop and Song Position Pointer" = "O LYNX segue o MIDI clock desta entrada: o andamento, Start / Continue / Stop e Song Position Pointer"
+"External sync offset (milliseconds)" = "Deslocamento da sincronização externa (milissegundos)"
+"Positive plays LYNX later than the clock, negative earlier" = "Positivo toca o LYNX mais tarde que o clock, negativo mais cedo"
+"No clock" = "Sem clock"
+"Clock is too fast!" = "Clock rápido demais!"
+"Receiving clock {0} BPM" = "Recebendo clock a {0} BPM"
+"playing" = "tocando"
+"The input must be on in Input devices above. Song time will match the clock." = "A entrada precisa estar ligada em Dispositivos de entrada acima. O tempo da música segue o clock."

+ 1 - 1
scripts/build-local.sh

@@ -35,7 +35,7 @@ CORE="$CORE src/core/ProjectSafety.cpp"
 # LYNX substitutes for missing third-party plugins (round 98)
 CORE="$CORE src/core/PluginSubstitutes.cpp"
 # settings pages, plugin manager and shortcut manager logic (round 82)
-CORE="$CORE src/core/Preferences.cpp"
+CORE="$CORE src/core/Preferences.cpp src/core/MidiSync.cpp"
 # user themes: the palette derived from an accent and a background (round 162d)
 CORE="$CORE src/core/ThemePalette.cpp"
 # layouts of the native plugin editors (round 93)

+ 1 - 1
scripts/build-windows-zig.sh

@@ -106,7 +106,7 @@ APP_SOURCES+=(src/core/MissingFiles.cpp src/core/ProjectSafety.cpp src/ui/Missin
 APP_SOURCES+=(src/core/PluginSubstitutes.cpp)
 # settings pages (General/Audio/MIDI), plugin manager, shortcut manager (round 82)
 APP_SOURCES+=(src/core/ThemePalette.cpp src/ui/ThemeSettings.cpp src/ui/ColourPicker.cpp)
-APP_SOURCES+=(src/core/Preferences.cpp src/ui/SettingsPages.cpp src/ui/PluginManager.cpp src/ui/ShortcutManager.cpp)
+APP_SOURCES+=(src/core/Preferences.cpp src/core/MidiSync.cpp src/engine/MidiSyncIo.cpp src/ui/SettingsPages.cpp src/ui/PluginManager.cpp src/ui/ShortcutManager.cpp)
 # spectral waveforms: band analysis, background cache and drawing
 APP_SOURCES+=(src/core/WaveAnalysis.cpp src/ui/WaveformView.cpp)
 # FL's Plucked!, Sawer and BeepMap engines (REA round 65)

+ 15 - 0
src/Main.cpp

@@ -438,6 +438,17 @@ public:
             return;
         }
 
+        if (args.contains ("--midisync-test"))
+        {
+            // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
+            const auto i = args.indexOf ("--midisync-test");
+            const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
+            const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
+            juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
+            quit();
+            return;
+        }
+
         if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
         {
             // diagnostics: driver types and output devices JUCE offers (without opening any)
@@ -459,6 +470,10 @@ public:
                 for (const auto& name : type->getDeviceNames (true))
                     report << "  input=" << name << "\n";
             }
+            for (const auto& d : juce::MidiInput::getAvailableDevices())
+                report << "midi-in=" << d.name << "\n";
+            for (const auto& d : juce::MidiOutput::getAvailableDevices())
+                report << "midi-out=" << d.name << "\n";
 
             const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
             juce::File (args[flag + 1].unquoted()).replaceWithText (report);

+ 417 - 0
src/core/MidiSync.cpp

@@ -0,0 +1,417 @@
+#include "core/MidiSync.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+
+namespace lynx::midisync
+{
+namespace
+{
+constexpr double ticksPerQuarter = 960.0;
+constexpr double ticksPerPulse = ticksPerQuarter / 24.0; // 40
+constexpr double ticksPerSixteenth = ticksPerQuarter / 4.0;
+} // namespace
+
+const char* syncTypeKey (SyncType type) noexcept
+{
+    switch (type)
+    {
+        case SyncType::midiClock: return "clock";
+        case SyncType::mtc24: return "mtc24";
+        case SyncType::mtc25: return "mtc25";
+        case SyncType::mtc30Drop: return "mtc30drop";
+        case SyncType::mtc30: return "mtc30";
+        case SyncType::mtc2997Drop: return "mtc2997drop";
+        case SyncType::mtc2997: return "mtc2997";
+    }
+    return "clock";
+}
+
+SyncType syncTypeFromKey (const std::string& key) noexcept
+{
+    for (int i = 0; i < syncTypeCount; ++i)
+        if (key == syncTypeKey ((SyncType) i))
+            return (SyncType) i;
+    return SyncType::midiClock;
+}
+
+const char* syncTypeName (SyncType type) noexcept
+{
+    switch (type)
+    {
+        case SyncType::midiClock: return "MIDI clock";
+        case SyncType::mtc24: return "MTC 24 fps";
+        case SyncType::mtc25: return "MTC 25 fps";
+        case SyncType::mtc30Drop: return "MTC 30 fps (drop)";
+        case SyncType::mtc30: return "MTC 30 fps (non-drop)";
+        case SyncType::mtc2997Drop: return "MTC 29.97 fps (drop)";
+        case SyncType::mtc2997: return "MTC 29.97 fps (non-drop)";
+    }
+    return "MIDI clock";
+}
+
+MtcRate mtcRate (SyncType type) noexcept
+{
+    switch (type)
+    {
+        case SyncType::mtc24: return { 24.0, 24, false, 0 };
+        case SyncType::mtc25: return { 25.0, 25, false, 1 };
+        case SyncType::mtc30Drop: return { 30.0, 30, true, 2 };
+        case SyncType::mtc30: return { 30.0, 30, false, 3 };
+        case SyncType::mtc2997Drop: return { 30000.0 / 1001.0, 30, true, 2 };
+        case SyncType::mtc2997: return { 30000.0 / 1001.0, 30, false, 3 };
+        case SyncType::midiClock: break;
+    }
+    return { 25.0, 25, false, 1 };
+}
+
+Timecode frameToTimecode (std::int64_t frame, const MtcRate& rate) noexcept
+{
+    frame = std::max<std::int64_t> (0, frame);
+    const auto n = (std::int64_t) rate.nominal;
+    if (rate.drop)
+    {
+        // 30-frame numbering with labels 0 and 1 dropped at each minute except every tenth: 17 982 frames per 10 min
+        const std::int64_t perTen = 10 * 60 * n - 9 * 2, perMinute = 60 * n - 2;
+        const auto tens = frame / perTen, rest = frame % perTen;
+        frame += 18 * tens + (rest > 1 ? 2 * ((rest - 2) / perMinute) : 0);
+    }
+    Timecode tc;
+    tc.frames = (int) (frame % n);
+    tc.seconds = (int) (frame / n % 60);
+    tc.minutes = (int) (frame / (n * 60) % 60);
+    tc.hours = (int) (frame / (n * 3600) % 24);
+    return tc;
+}
+
+std::int64_t timecodeToFrame (const Timecode& tc, const MtcRate& rate) noexcept
+{
+    const auto n = (std::int64_t) rate.nominal;
+    auto frame = ((std::int64_t) tc.hours * 3600 + tc.minutes * 60 + tc.seconds) * n + tc.frames;
+    if (rate.drop)
+    {
+        const auto minutes = (std::int64_t) tc.hours * 60 + tc.minutes;
+        frame -= 2 * (minutes - minutes / 10);
+    }
+    return frame;
+}
+
+std::uint8_t quarterFrameData (const Timecode& tc, int piece, int rateCode) noexcept
+{
+    int value = 0;
+    switch (piece & 7)
+    {
+        case 0: value = tc.frames & 0x0f; break;
+        case 1: value = (tc.frames >> 4) & 0x01; break;
+        case 2: value = tc.seconds & 0x0f; break;
+        case 3: value = (tc.seconds >> 4) & 0x03; break;
+        case 4: value = tc.minutes & 0x0f; break;
+        case 5: value = (tc.minutes >> 4) & 0x03; break;
+        case 6: value = tc.hours & 0x0f; break;
+        case 7: value = ((tc.hours >> 4) & 0x01) | ((rateCode & 3) << 1); break;
+        default: break;
+    }
+    return (std::uint8_t) (((piece & 7) << 4) | value);
+}
+
+void fullFrame (const Timecode& tc, int rateCode, std::uint8_t* out) noexcept
+{
+    const std::uint8_t m[10] { 0xf0, 0x7f, 0x7f, 0x01, 0x01, (std::uint8_t) (((rateCode & 3) << 5) | (tc.hours & 0x1f)),
+                               (std::uint8_t) (tc.minutes & 0x3f), (std::uint8_t) (tc.seconds & 0x3f), (std::uint8_t) (tc.frames & 0x1f), 0xf7 };
+    std::copy (m, m + 10, out);
+}
+
+int sppFor (double ticks) noexcept
+{
+    const auto sixteenths = std::ceil (std::max (0.0, ticks) / ticksPerSixteenth - 1.0e-6);
+    return (int) std::min (16383.0, sixteenths);
+}
+
+// --- generator ---------------------------------------------------------------------------------------------------
+void Generator::setType (SyncType t) noexcept
+{
+    if (t != syncType)
+    {
+        syncType = t;
+        reset();
+    }
+}
+
+void Generator::reset() noexcept
+{
+    wasPlaying = false;
+    nextPulseTicks = 0.0;
+    nextQuarter = 0;
+    mtcSeconds = 0.0;
+}
+
+void Generator::process (const Block& block, double songSeconds, BlockMessages& out) noexcept
+{
+    if (block.numSamples <= 0)
+        return;
+    if (syncType == SyncType::midiClock)
+        processClock (block, out);
+    else
+        processMtc (block, songSeconds, out);
+}
+
+void Generator::processClock (const Block& block, BlockMessages& out) noexcept
+{
+    if (! block.playing)
+    {
+        if (wasPlaying)
+            out.add (0, { 0xfc }); // Stop
+        wasPlaying = false;
+        return;
+    }
+
+    if (! wasPlaying || block.jumped)
+    {
+        if (wasPlaying)
+            out.add (0, { 0xfc }); // a jump while playing: stop, relocate, continue
+        if (block.startTicks < 0.5)
+        {
+            out.add (0, { 0xfa }); // Start (from the song's beginning)
+            nextPulseTicks = 0.0;
+        }
+        else
+        {
+            const auto spp = sppFor (block.startTicks);
+            out.add (0, { 0xf2, (std::uint8_t) (spp & 0x7f), (std::uint8_t) ((spp >> 7) & 0x7f) });
+            out.add (0, { 0xfb }); // Continue: the first clock after it is at the SPP
+            nextPulseTicks = spp * ticksPerSixteenth;
+        }
+        wasPlaying = true;
+    }
+
+    if (block.ticksPerSample <= 0.0)
+        return;
+    const auto end = block.startTicks + block.numSamples * block.ticksPerSample;
+    // (a pulse is due at the first sample whose position reaches it)
+    while (nextPulseTicks < end - 1.0e-9)
+    {
+        const auto at = std::ceil ((nextPulseTicks - block.startTicks) / block.ticksPerSample - 1.0e-9);
+        out.add (std::clamp ((int) at, 0, block.numSamples - 1), { 0xf8 });
+        nextPulseTicks += ticksPerPulse;
+        if (out.overflow)
+            break;
+    }
+}
+
+void Generator::processMtc (const Block& block, double songSeconds, BlockMessages& out) noexcept
+{
+    if (! block.playing)
+    {
+        wasPlaying = false; // MTC: the quarter frames stop, the receiver stops with them
+        return;
+    }
+    const auto rate = mtcRate (syncType);
+    const auto quarter = 1.0 / (rate.fps * 4.0);
+
+    if (! wasPlaying || block.jumped)
+    {
+        mtcSeconds = std::max (0.0, songSeconds);
+        const auto frame = (std::int64_t) std::floor (mtcSeconds * rate.fps + 1.0e-9);
+        Message m;
+        m.size = 10;
+        fullFrame (frameToTimecode (frame, rate), rate.code, m.bytes.data());
+        if (out.count < (int) out.items.size())
+            out.items[(std::size_t) out.count++] = m;
+        // the quarter frames resume at the next even frame (piece 0 of a sequence starts on an even frame)
+        auto first = (std::int64_t) std::ceil (mtcSeconds * rate.fps - 1.0e-9);
+        if (first % 2 != 0)
+            ++first;
+        nextQuarter = first * 4;
+        wasPlaying = true;
+    }
+
+    const auto blockSeconds = block.numSamples / block.sampleRate;
+    while (nextQuarter * quarter < mtcSeconds + blockSeconds - 1.0e-12)
+    {
+        const auto at = std::ceil ((nextQuarter * quarter - mtcSeconds) * block.sampleRate - 1.0e-6);
+        const auto piece = (int) (nextQuarter % 8);
+        const auto tc = frameToTimecode ((nextQuarter / 8) * 2, rate);
+        out.add (std::clamp ((int) at, 0, block.numSamples - 1), { 0xf1, quarterFrameData (tc, piece, rate.code) });
+        ++nextQuarter;
+        if (out.overflow)
+            break;
+    }
+    mtcSeconds += blockSeconds;
+}
+
+// --- receiver ----------------------------------------------------------------------------------------------------
+double fitBpm (const double* t, int count) noexcept
+{
+    if (count < 2)
+        return 0.0;
+    // least squares slope of time against pulse index
+    double meanX = (count - 1) * 0.5, meanY = 0.0;
+    for (int i = 0; i < count; ++i)
+        meanY += t[i];
+    meanY /= count;
+    double sxy = 0.0, sxx = 0.0;
+    for (int i = 0; i < count; ++i)
+    {
+        sxy += (i - meanX) * (t[i] - meanY);
+        sxx += (i - meanX) * (i - meanX);
+    }
+    const auto secondsPerPulse = sxx > 0.0 ? sxy / sxx : 0.0;
+    return secondsPerPulse > 0.0 ? 60.0 / (secondsPerPulse * 24.0) : 0.0;
+}
+
+void Receiver::reset() noexcept
+{
+    timeCount = timeHead = changeVotes = 0;
+    shownBpm = 0.0;
+    armed = false;
+    positionTicks = sppTicks = 0.0;
+    tempo.store (0.0);
+    lastPulse.store (-1.0);
+    lastPulseTicks.store (0.0);
+    pulseSeconds.store (0.0);
+    isRunning.store (false);
+    fast.store (false);
+}
+
+void Receiver::pushCommand (Command c, double ticks) noexcept
+{
+    commands.push ({ c, ticks });
+}
+
+bool Receiver::popCommand (Command& c, double& ticks) noexcept
+{
+    Pending p;
+    if (! commands.pop (p))
+        return false;
+    c = p.command;
+    ticks = p.ticks;
+    return true;
+}
+
+bool Receiver::receiving (double now) const noexcept
+{
+    const auto last = lastPulse.load (std::memory_order_relaxed);
+    return last >= 0.0 && now - last < 0.5;
+}
+
+double Receiver::ticksAt (double seconds) const noexcept
+{
+    const auto base = lastPulseTicks.load (std::memory_order_relaxed);
+    const auto last = lastPulse.load (std::memory_order_relaxed);
+    const auto period = pulseSeconds.load (std::memory_order_relaxed);
+    if (! running() || last < 0.0 || period <= 0.0)
+        return base;
+    // (extrapolated up to 0.1 s past the last pulse, at least one pulse: enough for the output latency, and a master
+    // that stops sending without a Stop doesn't run LYNX away)
+    return base + ticksPerPulse * std::clamp ((seconds - last) / period, 0.0, std::max (1.0, 0.1 / period));
+}
+
+void Receiver::pulse (double seconds) noexcept
+{
+    // tempo: the last `window` + 1 pulse times in a ring, oldest first when fitted
+    constexpr int size = window + 1;
+    times[(std::size_t) timeHead] = seconds;
+    timeHead = (timeHead + 1) % size;
+    timeCount = std::min (timeCount + 1, size);
+
+    std::array<double, size> ordered {};
+    for (int i = 0; i < timeCount; ++i)
+        ordered[(std::size_t) i] = times[(std::size_t) ((timeHead - timeCount + i + 2 * size) % size)];
+
+    // a tempo change: the mean of the last 6 intervals is more than 4 % off the fitted period on two pulses running
+    // (one late message makes one interval long and the next short, which the 6-interval mean absorbs). The fit then
+    // restarts from those 7 pulses, so the new tempo is followed within a few pulses instead of the whole window.
+    constexpr int recent = 6;
+    if (timeCount > recent + 4)
+    {
+        const auto fitted = fitBpm (ordered.data(), timeCount - recent);
+        const auto mean = (ordered[(std::size_t) (timeCount - 1)] - ordered[(std::size_t) (timeCount - 1 - recent)]) / recent;
+        const auto period = fitted > 0.0 ? 60.0 / (fitted * 24.0) : 0.0;
+        changeVotes = period > 0.0 && std::abs (mean / period - 1.0) > 0.04 ? changeVotes + 1 : 0;
+        if (changeVotes >= 2)
+        {
+            for (int i = 0; i <= recent; ++i)
+                times[(std::size_t) i] = ordered[(std::size_t) (timeCount - 1 - recent + i)];
+            timeCount = recent + 1;
+            timeHead = timeCount % size;
+            for (int i = 0; i < timeCount; ++i)
+                ordered[(std::size_t) i] = times[(std::size_t) i];
+            shownBpm = 0.0;
+            changeVotes = 0;
+        }
+    }
+
+    const auto estimate = fitBpm (ordered.data(), timeCount);
+    if (estimate > 0.0)
+    {
+        fast.store (estimate > 999.0, std::memory_order_relaxed);
+        // hysteresis: a steady clock with jitter shows one steady tempo; the period used for the position follows the
+        // estimate directly
+        if (shownBpm <= 0.0 || std::abs (estimate - shownBpm) > hysteresis)
+            shownBpm = estimate;
+        tempo.store (std::clamp (shownBpm, 10.0, 999.0), std::memory_order_relaxed);
+        pulseSeconds.store (60.0 / (estimate * 24.0), std::memory_order_relaxed);
+    }
+
+    if (armed)
+    {
+        armed = false;
+        positionTicks = sppTicks; // the first pulse after Start / Continue is at the song position
+        isRunning.store (true, std::memory_order_relaxed);
+    }
+    else if (isRunning.load (std::memory_order_relaxed))
+        positionTicks += ticksPerPulse;
+    lastPulseTicks.store (positionTicks, std::memory_order_relaxed);
+    lastPulse.store (seconds, std::memory_order_relaxed);
+}
+
+bool Receiver::feed (const std::uint8_t* bytes, int size, double seconds) noexcept
+{
+    if (size <= 0)
+        return false;
+    switch (bytes[0])
+    {
+        case 0xf8:
+            pulse (seconds);
+            return true;
+        case 0xfa: // Start: from the beginning, on the next pulse
+            sppTicks = 0.0;
+            armed = true;
+            pushCommand (Command::start, 0.0);
+            return true;
+        case 0xfb: // Continue: from the last Song Position Pointer, on the next pulse
+            armed = true;
+            pushCommand (Command::resume, sppTicks);
+            return true;
+        case 0xfc:
+            armed = false;
+            isRunning.store (false, std::memory_order_relaxed);
+            lastPulseTicks.store (positionTicks, std::memory_order_relaxed);
+            sppTicks = positionTicks; // a Continue without an SPP resumes where it stopped
+            pushCommand (Command::stop, positionTicks);
+            return true;
+        case 0xf2:
+            if (size < 3)
+                return true;
+            sppTicks = ((bytes[1] & 0x7f) | ((bytes[2] & 0x7f) << 7)) * ticksPerSixteenth;
+            positionTicks = sppTicks;
+            lastPulseTicks.store (positionTicks, std::memory_order_relaxed);
+            pushCommand (Command::locate, sppTicks);
+            return true;
+        default:
+            return false;
+    }
+}
+
+std::string statusText (const Receiver& r, double now)
+{
+    if (! r.receiving (now) || r.bpm() <= 0.0)
+        return "No clock";
+    if (r.tooFast())
+        return "Clock is too fast!";
+    char text[64];
+    std::snprintf (text, sizeof (text), "Receiving clock %.1f BPM%s", r.bpm(), r.running() ? ", playing" : "");
+    return text;
+}
+} // namespace lynx::midisync

+ 195 - 0
src/core/MidiSync.h

@@ -0,0 +1,195 @@
+#pragma once
+
+// MIDI synchronisation (REA round 165f, docs/analise/REA_rodada165f-midisync.md): FL Studio's Options › MIDI
+// "Send master sync" (MIDI clock + Song Position Pointer, or MIDI Time Code at 24 / 25 / 30 / 29.97 fps, drop or
+// non-drop) to an output and "External clock sync" (LYNX follows an incoming MIDI clock: tempo, Start / Continue /
+// Stop, Song Position Pointer). Pure logic, no devices: the engine feeds blocks and incoming bytes, tests check it.
+// Real-time safe: no allocation, no locks; fixed-capacity outputs.
+
+#include <array>
+#include <atomic>
+#include <cstdint>
+#include <string>
+
+#include "core/LiveEventQueue.h"
+
+namespace lynx::midisync
+{
+// FL's "Synchronization type" list (the order of its combo box, without the separator)
+enum class SyncType
+{
+    midiClock,
+    mtc24,
+    mtc25,
+    mtc30Drop,
+    mtc30,
+    mtc2997Drop,
+    mtc2997
+};
+constexpr int syncTypeCount = 7;
+const char* syncTypeKey (SyncType type) noexcept;     // stable name for the settings file ("clock", "mtc24", …)
+SyncType syncTypeFromKey (const std::string& key) noexcept;
+const char* syncTypeName (SyncType type) noexcept;    // English UI name, as FL's list
+
+// --- MIDI Time Code ---------------------------------------------------------------------------------------------
+struct MtcRate
+{
+    double fps = 25.0;   // real frames per second (29.97 = 30000 / 1001)
+    int nominal = 25;    // frames counted per second in the labels (30 for 29.97)
+    bool drop = false;   // drop-frame numbering (labels 0 and 1 skipped each minute except every 10th)
+    int code = 1;        // the rate bits in the hours byte: 0 = 24, 1 = 25, 2 = 30 drop, 3 = 30
+};
+MtcRate mtcRate (SyncType type) noexcept;
+
+struct Timecode
+{
+    int hours = 0, minutes = 0, seconds = 0, frames = 0;
+    bool operator== (const Timecode&) const = default;
+};
+// The label of frame number `frame` (0 = 00:00:00:00), drop-frame numbering when the rate says so.
+Timecode frameToTimecode (std::int64_t frame, const MtcRate& rate) noexcept;
+// The inverse (for tests and the receiver display).
+std::int64_t timecodeToFrame (const Timecode& tc, const MtcRate& rate) noexcept;
+// Quarter-frame message piece 0…7 (the data byte after 0xF1) for timecode `tc`.
+std::uint8_t quarterFrameData (const Timecode& tc, int piece, int rateCode) noexcept;
+// The full-frame SysEx F0 7F 7F 01 01 hh mm ss ff F7 (10 bytes) into `out`.
+void fullFrame (const Timecode& tc, int rateCode, std::uint8_t* out) noexcept;
+
+// --- what the generator sends -----------------------------------------------------------------------------------
+struct Message
+{
+    int sample = 0;                 // offset in the block it belongs to
+    std::uint8_t size = 0;
+    std::array<std::uint8_t, 10> bytes {};
+};
+
+template <int Capacity>
+struct MessageList
+{
+    std::array<Message, Capacity> items {};
+    int count = 0;
+    bool overflow = false;
+    void clear() noexcept
+    {
+        count = 0;
+        overflow = false;
+    }
+    void add (int sample, std::initializer_list<std::uint8_t> b) noexcept
+    {
+        if (count >= Capacity)
+        {
+            overflow = true;
+            return;
+        }
+        auto& m = items[(std::size_t) count++];
+        m.sample = sample;
+        m.size = 0;
+        for (auto v : b)
+            m.bytes[m.size++] = v;
+    }
+};
+using BlockMessages = MessageList<512>;
+
+// One audio block as the transport plays it.
+struct Block
+{
+    double startTicks = 0.0;      // position at the block's first sample (core ticks, 960 PPQ)
+    double ticksPerSample = 0.0;  // the tempo during the block
+    double sampleRate = 44100.0;
+    int numSamples = 0;
+    bool playing = false;
+    bool jumped = false;          // the position was moved before this block (seek, loop wrap) while playing
+};
+
+// Song Position Pointer value (MIDI beats = 16th notes) for a tick position; rounded up to the next 16th so the
+// first clock after Continue falls exactly on it.
+int sppFor (double ticks) noexcept;
+
+// Master sync generator for one output. Clock: 24 pulses per quarter note at the sample where the position crosses
+// each pulse, Start at 0 / SPP + Continue elsewhere, Stop when the transport stops, SPP + Continue after a jump.
+// MTC: quarter frames (4 per frame, 8 pieces over 2 frames, piece 0 on an even frame) from the song time, a full
+// frame on every start and locate.
+class Generator
+{
+public:
+    void setType (SyncType t) noexcept;
+    SyncType type() const noexcept { return syncType; }
+    void reset() noexcept;
+    // Appends this block's messages (sample offsets relative to the block). `songSeconds` = the song time of the
+    // block's first sample (MTC only; the engine computes it from the position and tempo).
+    void process (const Block& block, double songSeconds, BlockMessages& out) noexcept;
+
+private:
+    void processClock (const Block& block, BlockMessages& out) noexcept;
+    void processMtc (const Block& block, double songSeconds, BlockMessages& out) noexcept;
+
+    SyncType syncType = SyncType::midiClock;
+    bool wasPlaying = false;
+    double nextPulseTicks = 0.0;         // the next clock pulse position (multiple of 40 ticks)
+    std::int64_t nextQuarter = 0;        // MTC: the next quarter-frame index (frame * 4 + piece)
+    double mtcSeconds = 0.0;             // MTC: the song time at the next block's first sample
+};
+
+// --- external clock in ------------------------------------------------------------------------------------------
+// Fed by the MIDI thread with each real-time / SPP message and its time stamp (seconds, same clock as the engine's
+// Time::getMillisecondCounterHiRes()/1000). Publishes a smoothed tempo and a song position for the audio thread.
+class Receiver
+{
+public:
+    enum class Command : std::uint8_t
+    {
+        none,
+        start,
+        stop,
+        resume,
+        locate
+    };
+
+    // returns true if the message was a sync message (consumed)
+    bool feed (const std::uint8_t* bytes, int size, double seconds) noexcept;
+    void reset() noexcept;
+
+    // --- read from any thread (atomics) ---
+    double bpm() const noexcept { return tempo.load (std::memory_order_relaxed); }   // 0 = no clock yet
+    bool running() const noexcept { return isRunning.load (std::memory_order_relaxed); }
+    bool receiving (double now) const noexcept;                                         // a clock in the last 0.5 s
+    // The song position (ticks) the master is at at time `seconds`, while running: the last pulse's position plus
+    // the time since it at the measured tempo (extrapolated at most 0.1 s, or one pulse).
+    double ticksAt (double seconds) const noexcept;
+    // Transport commands for the audio thread (start / stop / continue / SPP), oldest first.
+    bool popCommand (Command& c, double& ticks) noexcept;
+    bool tooFast() const noexcept { return fast.load (std::memory_order_relaxed); }   // FL's "Clock is too fast !"
+
+    static constexpr int window = 96;          // pulses in the tempo estimate (four beats)
+    static constexpr double hysteresis = 0.1; // BPM
+
+private:
+    void pushCommand (Command c, double ticks) noexcept;
+    void pulse (double seconds) noexcept;
+
+    // MIDI thread only
+    std::array<double, window + 1> times {};
+    int timeCount = 0, timeHead = 0, changeVotes = 0;
+    double shownBpm = 0.0;
+    bool armed = false;            // after Start/Continue: the next pulse is the first one played
+    double positionTicks = 0.0;    // the master's position (ticks) at the last pulse
+    double sppTicks = 0.0;
+
+    std::atomic<double> tempo { 0.0 }, lastPulse { -1.0 }, lastPulseTicks { 0.0 }, pulseSeconds { 0.0 };
+    std::atomic<bool> isRunning { false }, fast { false };
+    struct Pending
+    {
+        Command command = Command::none;
+        double ticks = 0.0;
+    };
+    SpscQueue<Pending, 64> commands;
+};
+
+// FL's status text: "Receiving clock 120.0 BPM" / "No clock" (the UI translates the parts).
+std::string statusText (const Receiver& r, double now);
+
+// Tempo smoothing: a least-squares fit of the last `window` pulse times (robust to per-message jitter), then
+// hysteresis: the published tempo moves only when the estimate differs by more than `threshold` BPM, so a steady
+// clock with jitter shows a steady tempo. Exposed for tests.
+double fitBpm (const double* times, int count) noexcept;
+} // namespace lynx::midisync

+ 47 - 0
src/core/Preferences.cpp

@@ -342,6 +342,25 @@ void MidiPrefs::setInput (const MidiInputPrefs& in)
         inputs.push_back (in);
 }
 
+MidiOutputPrefs MidiPrefs::output (const std::string& name) const
+{
+    for (const auto& o : outputs)
+        if (o.name == name)
+            return o;
+    MidiOutputPrefs d;
+    d.name = name;
+    return d;
+}
+
+void MidiPrefs::setOutput (const MidiOutputPrefs& out)
+{
+    MidiOutputPrefs defaults;
+    defaults.name = out.name;
+    outputs.erase (std::remove_if (outputs.begin(), outputs.end(), [&] (const MidiOutputPrefs& o) { return o.name == out.name; }), outputs.end());
+    if (! (out == defaults))
+        outputs.push_back (out);
+}
+
 bool MidiPrefs::accepts (const std::string& device, int channel) const
 {
     const auto i = input (device);
@@ -386,6 +405,13 @@ std::string MidiPrefs::toText() const
     // input=<enabled>|<midi channel>|<target>|<device name>
     for (const auto& i : inputs)
         out += "input=" + std::string (i.enabled ? "1" : "0") + "|" + std::to_string (i.midiChannel) + "|" + std::to_string (i.target) + "|" + i.name + "\n";
+    // output=<master sync>|<sync type>|<offset ms>|<all notes off>|<device name>
+    for (const auto& o : outputs)
+        out += "output=" + std::string (o.masterSync ? "1" : "0") + "|" + o.syncType + "|" + std::to_string (o.offsetMs) + "|"
+               + (o.allNotesOff ? "1" : "0") + "|" + o.name + "\n";
+    // clockin=<offset ms>|<device name>
+    if (! clockInput.empty() || clockOffsetMs != 0)
+        out += "clockin=" + std::to_string (clockOffsetMs) + "|" + clockInput + "\n";
     // link=<cc>|<channel>|<target kind>|<index>|<slot>|<param>
     for (const auto& l : globalLinks)
         out += "link=" + std::to_string (l.cc) + "|" + std::to_string (l.channel) + "|" + std::to_string (l.kind) + "|" + std::to_string (l.index)
@@ -428,6 +454,27 @@ MidiPrefs MidiPrefs::fromText (const std::string& text)
             i.name = parts[3];
             p.setInput (i);
         }
+        else if (key == "output")
+        {
+            const auto parts = split (value, '|', 5);
+            if (parts.size() != 5 || parts[4].empty())
+                continue;
+            MidiOutputPrefs o;
+            o.masterSync = trim (parts[0]) == "1";
+            o.syncType = trim (parts[1]);
+            o.offsetMs = std::clamp (toInt (trim (parts[2]), 0), -1000, 1000);
+            o.allNotesOff = trim (parts[3]) == "1";
+            o.name = parts[4];
+            p.setOutput (o);
+        }
+        else if (key == "clockin")
+        {
+            const auto parts = split (value, '|', 2);
+            if (parts.size() != 2)
+                continue;
+            p.clockOffsetMs = std::clamp (toInt (trim (parts[0]), 0), -1000, 1000);
+            p.clockInput = parts[1];
+        }
         else if (key == "link")
         {
             const auto parts = split (value, '|', 6);

+ 17 - 0
src/core/Preferences.h

@@ -128,9 +128,24 @@ struct GlobalLink
     bool operator== (const GlobalLink&) const = default;
 };
 
+// An output device (FL's Options › MIDI "Output" panel, REA round 165f): master sync and all-notes-off.
+struct MidiOutputPrefs
+{
+    std::string name;          // the device name
+    bool masterSync = false;   // "Send master sync"
+    std::string syncType = "clock"; // midisync::syncTypeKey: MIDI clock + SPP, or an MTC rate
+    int offsetMs = 0;          // "Master sync offset (milliseconds)", -1000…1000 (later = positive)
+    bool allNotesOff = false;  // "Send all notes off" on init and after an export
+
+    bool operator== (const MidiOutputPrefs&) const = default;
+};
+
 struct MidiPrefs
 {
     std::vector<MidiInputPrefs> inputs; // the devices the user changed (others use the defaults)
+    std::vector<MidiOutputPrefs> outputs; // the output devices the user changed
+    std::string clockInput;             // "External clock sync": the input LYNX follows ("" = off)
+    int clockOffsetMs = 0;              // "External sync offset (milliseconds)", -1000…1000
     std::vector<GlobalLink> globalLinks;
     VelocityCurve velocity = VelocityCurve::linear;
     bool pickup = false;                // a controller takes over a parameter only once it reaches its value
@@ -138,6 +153,8 @@ struct MidiPrefs
     // The settings of a device (the defaults when it was never changed).
     MidiInputPrefs input (const std::string& name) const;
     void setInput (const MidiInputPrefs& input);
+    MidiOutputPrefs output (const std::string& name) const;
+    void setOutput (const MidiOutputPrefs& output);
 
     // Should a message on MIDI channel `channel` (1..16) from `device` be played?
     bool accepts (const std::string& device, int channel) const;

+ 2 - 2
src/core/RackRenderer.cpp

@@ -1924,9 +1924,9 @@ void RackRenderer::process (const RackState* state,
     resumeAudio = playing && (! wasPlaying || jumped);
     wasPlaying = playing;
     // tempo automation: the tempo holds for the whole block (evaluated at its start)
-    bpm = state->song.bpm;
+    bpm = tempoOverride > 0.0 ? tempoOverride : state->song.bpm;
 
-    if (state->tempoAutomation >= 0 && state->song.mode == PlayMode::song && ! isSlotOverridden (state->tempoAutomation))
+    if (tempoOverride <= 0.0 && state->tempoAutomation >= 0 && state->song.mode == PlayMode::song && ! isSlotOverridden (state->tempoAutomation))
     {
         const auto length = (double) std::max<std::int64_t> (1, state->schedule.songLength);
         const auto& clips = state->automationClips[(std::size_t) state->tempoAutomation];

+ 3 - 0
src/core/RackRenderer.h

@@ -300,6 +300,8 @@ public:
 
     // Tempo used in the last block (changes with tempo automation). The transport advances with it.
     double currentBpm() const noexcept { return bpm; }
+    // > 0: the tempo of an external MIDI clock LYNX follows (round 165f), over the song's tempo and its automation
+    void setTempoOverride (double b) noexcept { tempoOverride = b; }
 
     // Events of the last block (for tests and diagnostics).
     const EventBuffer& lastEvents() const noexcept { return events; }
@@ -325,6 +327,7 @@ private:
 
     double sampleRate = 44100.0;
     double bpm = 120.0;
+    double tempoOverride = 0.0;
     bool wasPlaying = false;
     double expectedTick = -1.0; // where the next block should start, to detect jumps
     bool resumeAudio = false;

+ 18 - 0
src/engine/AudioEngine.cpp

@@ -260,6 +260,8 @@ AudioEngine::AudioEngine (bool openAudioDevice)
         prefetcher = std::make_unique<StreamPrefetcher> (transport);
         prefetcher->update (song, samples);
         enableAllMidiInputs();
+        midiSync.configure (midiPrefs);
+        midiSync.sendAllNotesOff(); // FL's "Send all notes off": on init and after a render
         deviceManager.addMidiInputDeviceCallback ({}, this); // {} = all inputs enabled
         midiDevicesChanged = juce::MidiDeviceListConnection::make ([this] { enableAllMidiInputs(); });
     }
@@ -1586,6 +1588,10 @@ void AudioEngine::handleIncomingMidiMessage (juce::MidiInput* source, const juce
     if (! device.enabled)
         return;
 
+    // the external clock LYNX follows (round 165f): clock, start / stop / continue, song position
+    if (m.getRawDataSize() > 0 && (m.getRawData()[0] >= 0xf2) && source != nullptr && midiSync.handleInput (source->getName(), m))
+        return;
+
     midiActivity.fetch_add (1, std::memory_order_relaxed); // the toolbar's MIDI input light
 
     if (device.midiChannel != 0 && m.getChannel() != device.midiChannel)
@@ -1733,7 +1739,10 @@ void AudioEngine::setMidiPrefs (const prefs::MidiPrefs& p, bool save)
     if (! p.pickup)
         pickups.clear();
     if (prefetcher != nullptr) // (only with an audio device: the real app)
+    {
         enableAllMidiInputs();
+        midiSync.configure (p);
+    }
     if (save)
         midiSettingsFile().replaceWithText (juce::String (p.toText()));
     sendChangeMessage();
@@ -3101,6 +3110,8 @@ std::shared_ptr<Effect> AudioEngine::getEffect (int track, int slot) const
 
 void AudioEngine::setPluginsRenderMode (bool offline)
 {
+    if (! offline)
+        midiSync.sendAllNotesOff(); // FL's "Send all notes off": after a render
     // FL's "Notify about rendering mode" off: that plugin is not told (round 149); "Reset plugin when FL Studio
     // resets": reset as the export starts (round 151)
     for (std::size_t i = 0; i < song.channels.size(); ++i)
@@ -3230,6 +3241,9 @@ void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputCha
     if (const auto target = transport.seekRequest.exchange (-1.0); target >= 0.0)
         transport.positionTicks.store (target);
 
+    // an external MIDI clock moves the transport (round 165f)
+    midiSync.beginBlock (transport, callbackStart, numSamples);
+
     // With the loop region on, the block is split at the loop end and the position jumps back to
     // its start (the nodes see a jump and release their notes, as in FL).
     // the audio editor's input recording (nothing happens unless it chose the input)
@@ -3324,6 +3338,9 @@ void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputCha
         for (int ch = 0; ch < numOutputChannels; ++ch)
             outputs[(std::size_t) ch] = outputChannelData[ch] != nullptr ? outputChannelData[ch] + done : nullptr;
 
+        // master sync out (round 165f): this part's clock / MTC messages, time-stamped for the sender thread
+        midiSync.subBlock (transport.positionTicks.load (std::memory_order_relaxed), tps, n, done, playing);
+
         player.audioDeviceIOCallbackWithContext (inputs.data(), numInputChannels, outputs.data(), numOutputChannels, n, context);
         routeOutputs (outputs.data(), numOutputChannels, n);
 
@@ -3395,6 +3412,7 @@ void AudioEngine::audioDeviceAboutToStart (juce::AudioIODevice* device)
     rtStats.deviceRestarted();
     rt::resetForNewDevice();
     transport.sampleRate.store (device->getCurrentSampleRate());
+    midiSync.deviceStarted (device->getCurrentSampleRate(), device->getCurrentBufferSizeSamples(), device->getOutputLatencyInSamples());
     // FL's fixed size buffers: 2 ms, or the device buffer with "Process maximum size buffers" (REA round 134)
     setFixedPluginBlock (device->getCurrentBufferSizeSamples(), device->getCurrentSampleRate());
 

+ 4 - 0
src/engine/AudioEngine.h

@@ -18,6 +18,7 @@
 #include "core/Recorder.h"
 #include "core/TakeRecording.h"
 #include "core/WorkerPool.h"
+#include "engine/MidiSyncIo.h"
 #include "core/RackRenderer.h"
 #include "core/RtStats.h"
 #include "core/FlpImport.h"
@@ -338,6 +339,8 @@ public:
     const prefs::MidiPrefs& getMidiPrefs() const noexcept { return midiPrefs; }
     // Applies them (and saves them in %APPDATA%\LYNX\midi-settings.txt when `save`).
     void setMidiPrefs (const prefs::MidiPrefs& prefs, bool save = true);
+    // master sync out / external clock in / all notes off (round 165f)
+    MidiSyncIo& getMidiSync() noexcept { return midiSync; }
 
     // How many undo steps are kept (Settings › General).
     void setUndoLevels (int levels);
@@ -550,6 +553,7 @@ private:
     juce::AudioProcessorGraph graph;
     juce::AudioProcessorPlayer player;
     Transport transport;
+    MidiSyncIo midiSync; // (before the MIDI callbacks and the audio callback use it)
     SampleLibrary samples;
     LiveEventQueue liveEvents;   // UI -> audio
     LiveEventQueue midiEvents;   // MIDI thread -> audio

+ 2 - 1
src/engine/ChannelRackProcessor.cpp

@@ -26,6 +26,7 @@ void ChannelRackProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce:
     const auto* state = exchange.acquire();
     const auto playing = transport.playing.load (std::memory_order_relaxed);
     const auto startTick = transport.positionTicks.load (std::memory_order_relaxed);
+    renderer.setTempoOverride (transport.externalBpm.load (std::memory_order_relaxed));
 
     if (buffer.getNumChannels() >= 2)
     {
@@ -48,7 +49,7 @@ void ChannelRackProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce:
     }
 
     // tempo automation: the transport advances at the tempo the renderer used
-    if (state != nullptr && state->tempoAutomation >= 0)
+    if (state != nullptr && state->tempoAutomation >= 0 && transport.externalBpm.load (std::memory_order_relaxed) <= 0.0)
         transport.bpm.store (renderer.currentBpm(), std::memory_order_relaxed);
 }
 } // namespace lynx

+ 464 - 0
src/engine/MidiSyncIo.cpp

@@ -0,0 +1,464 @@
+#include "engine/MidiSyncIo.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <deque>
+#include <mutex>
+#include <random>
+#include <thread>
+
+#if JUCE_WINDOWS
+extern "C" __declspec (dllimport) unsigned int __stdcall timeBeginPeriod (unsigned int);
+extern "C" __declspec (dllimport) unsigned int __stdcall timeEndPeriod (unsigned int);
+#endif
+
+namespace lynx
+{
+namespace
+{
+void atomicMax (std::atomic<double>& a, double v) noexcept
+{
+    auto now = a.load (std::memory_order_relaxed);
+    while (v > now && ! a.compare_exchange_weak (now, v, std::memory_order_relaxed))
+    {
+    }
+}
+
+void atomicAdd (std::atomic<double>& a, double v) noexcept
+{
+    auto now = a.load (std::memory_order_relaxed);
+    while (! a.compare_exchange_weak (now, now + v, std::memory_order_relaxed))
+    {
+    }
+}
+} // namespace
+
+MidiSyncIo::MidiSyncIo() : juce::Thread ("LYNX MIDI sync") {}
+
+MidiSyncIo::~MidiSyncIo()
+{
+    stopThread (2000);
+    const juce::ScopedLock lock (outputLock);
+    for (auto& s : slots)
+        s.device.reset();
+}
+
+void MidiSyncIo::configure (const prefs::MidiPrefs& prefs, bool devices, bool dryRun)
+{
+    dry.store (dryRun);
+    {
+        const juce::SpinLock::ScopedLockType lock (clockNameLock);
+        clockName = juce::String::fromUTF8 (prefs.clockInput.c_str());
+    }
+    clockOffsetMs.store (juce::jlimit (-1000, 1000, prefs.clockOffsetMs));
+    if (following.exchange (! prefs.clockInput.empty()) != ! prefs.clockInput.empty())
+        clockIn.reset();
+
+    // the outputs that need a device: sync or notes off on
+    std::vector<prefs::MidiOutputPrefs> wanted;
+    for (const auto& o : prefs.outputs)
+        if (o.masterSync || o.allNotesOff)
+            wanted.push_back (o);
+    if ((int) wanted.size() > maxOutputs)
+        wanted.resize (maxOutputs);
+
+    const auto available = devices ? juce::MidiOutput::getAvailableDevices() : juce::Array<juce::MidiDeviceInfo>();
+    auto any = false;
+    for (int i = 0; i < maxOutputs; ++i)
+    {
+        auto& slot = slots[(std::size_t) i];
+        const prefs::MidiOutputPrefs* want = i < (int) wanted.size() ? &wanted[(std::size_t) i] : nullptr;
+        const auto sameDevice = want != nullptr && slot.name == want->name && (slot.device != nullptr || ! devices);
+        if (! sameDevice)
+        {
+            slot.active.store (false);
+            std::unique_ptr<juce::MidiOutput> opened;
+            if (want != nullptr && devices)
+                for (const auto& d : available)
+                    if (d.name.toStdString() == want->name)
+                    {
+                        opened = juce::MidiOutput::openDevice (d.identifier);
+                        break;
+                    }
+            {
+                const juce::ScopedLock lock (outputLock);
+                slot.device = std::move (opened);
+            }
+            slot.name = want != nullptr ? want->name : std::string();
+        }
+        slot.sync = want != nullptr && want->masterSync;
+        slot.notesOff = want != nullptr && want->allNotesOff;
+        const auto type = (int) midisync::syncTypeFromKey (want != nullptr ? want->syncType : std::string());
+        if (slot.type.exchange (type) != type || ! sameDevice)
+            slot.generation.fetch_add (1);
+        slot.offsetMs.store (want != nullptr ? juce::jlimit (-1000, 1000, want->offsetMs) : 0);
+        slot.active.store (slot.sync && (slot.device != nullptr || ! devices));
+        any = any || slot.active.load();
+    }
+    anySync.store (any);
+    if ((devices || dryRun) && any && ! isThreadRunning())
+        startThread (juce::Thread::Priority::highest);
+}
+
+void MidiSyncIo::sendAllNotesOff()
+{
+    const juce::ScopedLock lock (outputLock);
+    for (auto& s : slots)
+        if (s.notesOff && s.device != nullptr)
+            for (int ch = 1; ch <= 16; ++ch)
+            {
+                s.device->sendMessageNow (juce::MidiMessage::controllerEvent (ch, 64, 0));
+                s.device->sendMessageNow (juce::MidiMessage::allNotesOff (ch));
+            }
+}
+
+void MidiSyncIo::deviceStarted (double rate, int bufferSize, int outputLatencySamples) noexcept
+{
+    sampleRate = rate > 0.0 ? rate : 44100.0;
+    // the audio of a block computed now is heard one buffer plus the device's latency later: the sync messages for
+    // its samples are due then
+    latencyMs = 1000.0 * (bufferSize + std::max (0, outputLatencySamples)) / sampleRate;
+    predictedMs = -1.0;
+    for (auto& s : slots)
+        s.generator.reset();
+}
+
+void MidiSyncIo::beginBlock (Transport& transport, double callbackMs, int numSamples) noexcept
+{
+    // the block clock: callbacks wake up with jitter, the samples don't. Follow the sample count and pull towards
+    // the callback times slowly; resynchronise after a gap (xrun, device restart).
+    if (predictedMs < 0.0 || std::abs (callbackMs - predictedMs) > 50.0)
+        blockStartMs = callbackMs;
+    else
+        blockStartMs = predictedMs + 0.02 * (callbackMs - predictedMs);
+    predictedMs = blockStartMs + 1000.0 * numSamples / sampleRate;
+
+    if (! following.load (std::memory_order_relaxed))
+    {
+        if (wasFollowing)
+            transport.externalBpm.store (0.0, std::memory_order_relaxed);
+        wasFollowing = false;
+        waitingFirstPulse = false;
+        appliedBpm.store (0.0, std::memory_order_relaxed);
+        return;
+    }
+    wasFollowing = true;
+
+    midisync::Receiver::Command command;
+    double ticks = 0.0;
+    while (clockIn.popCommand (command, ticks))
+        switch (command)
+        {
+            case midisync::Receiver::Command::start:
+            case midisync::Receiver::Command::resume:
+                transport.playing.store (false, std::memory_order_relaxed);
+                transport.positionTicks.store (ticks, std::memory_order_relaxed);
+                waitingFirstPulse = true;
+                break;
+            case midisync::Receiver::Command::stop:
+                transport.playing.store (false, std::memory_order_relaxed);
+                waitingFirstPulse = false;
+                break;
+            case midisync::Receiver::Command::locate:
+                if (! transport.playing.load (std::memory_order_relaxed))
+                    transport.positionTicks.store (ticks, std::memory_order_relaxed);
+                break;
+            case midisync::Receiver::Command::none: break;
+        }
+
+    if (waitingFirstPulse && clockIn.running())
+    {
+        waitingFirstPulse = false;
+        transport.playing.store (true, std::memory_order_relaxed);
+    }
+
+    const auto nowSeconds = blockStartMs * 0.001;
+    const auto bpm = clockIn.receiving (nowSeconds) ? clockIn.bpm() : 0.0;
+    auto applied = bpm;
+    if (bpm > 0.0 && clockIn.running() && transport.playing.load (std::memory_order_relaxed))
+    {
+        // phase lock: the block's first sample is heard `latencyMs` from now; it should then be where the master is
+        // (plus the user's offset: positive = LYNX later)
+        const auto target = clockIn.ticksAt (nowSeconds + (latencyMs - clockOffsetMs.load (std::memory_order_relaxed)) * 0.001);
+        const auto position = transport.positionTicks.load (std::memory_order_relaxed);
+        const auto error = target - position;
+        if (std::abs (error) > 480.0) // half a beat off (a jump on the master's side): relocate
+            transport.positionTicks.store (target, std::memory_order_relaxed);
+        else // pull in within ~0.5 s, at most ±5 % of the tempo
+            applied = bpm * std::clamp (1.0 + error / (bpm * 16.0 * 0.5), 0.95, 1.05);
+    }
+    transport.externalBpm.store (applied, std::memory_order_relaxed);
+    appliedBpm.store (bpm, std::memory_order_relaxed);
+}
+
+void MidiSyncIo::subBlock (double startTicks, double ticksPerSample, int numSamples, int offset, bool playing) noexcept
+{
+    if (! anySync.load (std::memory_order_relaxed))
+        return;
+    const auto t0 = juce::Time::getHighResolutionTicks();
+    for (auto& slot : slots)
+    {
+        if (! slot.active.load (std::memory_order_relaxed))
+            continue;
+        if (const auto g = slot.generation.load (std::memory_order_acquire); g != slot.seenGeneration)
+        {
+            slot.seenGeneration = g;
+            slot.generator.reset();
+            slot.generator.setType ((midisync::SyncType) slot.type.load (std::memory_order_relaxed));
+        }
+        midisync::Block block;
+        block.startTicks = startTicks;
+        block.ticksPerSample = ticksPerSample;
+        block.sampleRate = sampleRate;
+        block.numSamples = numSamples;
+        block.playing = playing;
+        scratch.clear();
+        const auto songSeconds = ticksPerSample > 0.0 ? startTicks / (ticksPerSample * sampleRate) : 0.0;
+        slot.generator.process (block, songSeconds, scratch);
+        const auto base = blockStartMs + latencyMs + slot.offsetMs.load (std::memory_order_relaxed);
+        for (int i = 0; i < scratch.count; ++i)
+        {
+            const auto& m = scratch.items[(std::size_t) i];
+            if (! slot.queue.push ({ base + 1000.0 * (offset + m.sample) / sampleRate, m }))
+                droppedCount.fetch_add (1, std::memory_order_relaxed);
+        }
+    }
+    const auto us = 1.0e6 * juce::Time::highResolutionTicksToSeconds (juce::Time::getHighResolutionTicks() - t0);
+    atomicAdd (blockSum, us);
+    atomicMax (blockMax, us);
+    blockN.fetch_add (1, std::memory_order_relaxed);
+}
+
+void MidiSyncIo::run()
+{
+#if JUCE_WINDOWS
+    timeBeginPeriod (1); // 1 ms sleeps for this thread's waits
+#endif
+    std::array<std::deque<Timed>, maxOutputs> pending;
+    while (! threadShouldExit())
+    {
+        auto any = false;
+        for (int i = 0; i < maxOutputs; ++i)
+        {
+            Timed t;
+            while (slots[(std::size_t) i].queue.pop (t))
+                pending[(std::size_t) i].push_back (t);
+            any = any || ! pending[(std::size_t) i].empty();
+        }
+        if (! any)
+        {
+            if (! anySync.load())
+                wait (50);
+            else
+                std::this_thread::sleep_for (std::chrono::microseconds (500));
+            continue;
+        }
+
+        auto now = juce::Time::getMillisecondCounterHiRes();
+        auto next = now + 1000.0;
+        {
+            const juce::ScopedLock lock (outputLock);
+            for (int i = 0; i < maxOutputs; ++i)
+            {
+                auto& queue = pending[(std::size_t) i];
+                auto* device = slots[(std::size_t) i].device.get();
+                while (! queue.empty() && queue.front().dueMs <= now + 0.05)
+                {
+                    const auto& m = queue.front().message;
+                    if (device != nullptr || dry.load (std::memory_order_relaxed))
+                    {
+                        if (device != nullptr)
+                            device->sendMessageNow (juce::MidiMessage (m.bytes.data(), (int) m.size));
+                        now = juce::Time::getMillisecondCounterHiRes();
+                        const auto late = std::max (0.0, now - queue.front().dueMs);
+                        atomicAdd (lateSum, late);
+                        atomicMax (lateMax, late);
+                        lateN.fetch_add (1, std::memory_order_relaxed);
+                        sentCount.fetch_add (1, std::memory_order_relaxed);
+                    }
+                    queue.pop_front();
+                }
+                if (! queue.empty())
+                    next = std::min (next, queue.front().dueMs);
+            }
+        }
+        // sleep until shortly before the next message, then in short steps
+        const auto wait = next - juce::Time::getMillisecondCounterHiRes();
+        if (wait > 2.0)
+            std::this_thread::sleep_for (std::chrono::microseconds ((int) ((wait - 1.0) * 1000.0)));
+        else if (wait > 0.05)
+            std::this_thread::sleep_for (std::chrono::microseconds (100));
+    }
+#if JUCE_WINDOWS
+    timeEndPeriod (1);
+#endif
+}
+
+bool MidiSyncIo::handleInput (const juce::String& device, const juce::MidiMessage& m) noexcept
+{
+    if (! following.load (std::memory_order_relaxed))
+        return false;
+    {
+        const juce::SpinLock::ScopedLockType lock (clockNameLock);
+        if (device != clockName)
+            return false;
+    }
+    // (JUCE time-stamps input in seconds on Time::getMillisecondCounterHiRes()'s clock)
+    return clockIn.feed (m.getRawData(), m.getRawDataSize(), m.getTimeStamp());
+}
+
+std::string MidiSyncIo::clockStatus() const
+{
+    return midisync::statusText (clockIn, juce::Time::getMillisecondCounterHiRes() * 0.001);
+}
+
+double MidiSyncIo::followedBpm() const noexcept
+{
+    return appliedBpm.load (std::memory_order_relaxed);
+}
+
+MidiSyncIo::Stats MidiSyncIo::stats() const
+{
+    // the last second's numbers (read and reset at most once a second)
+    const auto now = juce::Time::getMillisecondCounterHiRes();
+    if (now - lastStatsMs < 1000.0)
+        return lastStats;
+    lastStatsMs = now;
+    auto& self = const_cast<MidiSyncIo&> (*this);
+    Stats s;
+    s.sent = sentCount.load();
+    s.dropped = droppedCount.load();
+    const auto ln = self.lateN.exchange (0);
+    s.meanLateMs = ln > 0 ? self.lateSum.exchange (0.0) / (double) ln : 0.0;
+    s.maxLateMs = self.lateMax.exchange (0.0);
+    const auto bn = self.blockN.exchange (0);
+    s.meanBlockUs = bn > 0 ? self.blockSum.exchange (0.0) / (double) bn : 0.0;
+    s.maxBlockUs = self.blockMax.exchange (0.0);
+    lastStats = s;
+    return s;
+}
+juce::String MidiSyncIo::selfTest (const juce::String& outputName, const juce::String& inputName)
+{
+    juce::String report;
+    // 1. in memory: the generator's clock (time-stamped with ±0.5 ms of jitter) followed by a receiver
+    {
+        std::mt19937 random (165);
+        std::uniform_real_distribution<double> jitter (-0.0005, 0.0005);
+        for (const auto bpm : { 90.0, 120.0, 174.0 })
+        {
+            midisync::Generator g;
+            midisync::Receiver r;
+            const double rate = 48000.0, tps = bpm * 960.0 / (60.0 * rate);
+            double ticks = 0.0;
+            std::int64_t sample = 0;
+            midisync::BlockMessages out;
+            for (int b = 0; b < 48000 * 8 / 256; ++b)
+            {
+                midisync::Block block;
+                block.startTicks = ticks;
+                block.ticksPerSample = tps;
+                block.sampleRate = rate;
+                block.numSamples = 256;
+                block.playing = true;
+                out.clear();
+                g.process (block, 0.0, out);
+                for (int i = 0; i < out.count; ++i)
+                    r.feed (out.items[(std::size_t) i].bytes.data(), out.items[(std::size_t) i].size,
+                            (double) (sample + out.items[(std::size_t) i].sample) / rate + jitter (random));
+                ticks += 256 * tps;
+                sample += 256;
+            }
+            const auto positionError = r.ticksAt ((double) sample / rate) - ticks;
+            report << "loopback bpm=" << bpm << " received=" << juce::String (r.bpm(), 3) << " error=" << juce::String (r.bpm() - bpm, 3)
+                   << " position error ticks=" << juce::String (positionError, 2) << " running=" << (r.running() ? 1 : 0) << "\n";
+        }
+    }
+
+    // 2. the sender thread at real time
+    MidiSyncIo io;
+    prefs::MidiPrefs p;
+    prefs::MidiOutputPrefs o;
+    o.name = outputName.isNotEmpty() ? outputName.toStdString() : std::string ("(dry run)");
+    o.masterSync = true;
+    p.setOutput (o);
+    const auto real = outputName.isNotEmpty();
+    io.configure (p, real, ! real);
+    report << "output=" << (real ? outputName : juce::String ("(dry run, timed without a device)")) << " opened=" << (io.sending() ? 1 : 0) << "\n";
+    for (const auto& d : juce::MidiOutput::getAvailableDevices())
+        report << "  midi-out=" << d.name << "\n";
+    for (const auto& d : juce::MidiInput::getAvailableDevices())
+        report << "  midi-in=" << d.name << "\n";
+
+    // the input side of a loopback: a receiver fed from the input callback
+    struct In final : juce::MidiInputCallback
+    {
+        midisync::Receiver receiver;
+        std::vector<double> times;
+        std::mutex lock;
+        void handleIncomingMidiMessage (juce::MidiInput*, const juce::MidiMessage& m) override
+        {
+            receiver.feed (m.getRawData(), m.getRawDataSize(), m.getTimeStamp());
+            if (m.getRawDataSize() > 0 && m.getRawData()[0] == 0xf8)
+            {
+                const std::lock_guard<std::mutex> g (lock);
+                times.push_back (juce::Time::getMillisecondCounterHiRes());
+            }
+        }
+    } in;
+    std::unique_ptr<juce::MidiInput> input;
+    if (inputName.isNotEmpty())
+        for (const auto& d : juce::MidiInput::getAvailableDevices())
+            if (d.name == inputName)
+                input = juce::MidiInput::openDevice (d.identifier, &in);
+    if (input != nullptr)
+        input->start();
+
+    if (io.sending())
+    {
+        Transport transport;
+        transport.sampleRate.store (48000.0);
+        transport.bpm.store (120.0);
+        transport.playing.store (true);
+        io.deviceStarted (48000.0, 256, 0);
+        const auto start = juce::Time::getMillisecondCounterHiRes();
+        for (int b = 0; b < 48000 * 5 / 256; ++b)
+        {
+            // wake up like an audio callback (with the scheduler's jitter), on the block's due time
+            const auto due = start + b * 256.0 * 1000.0 / 48000.0;
+            while (juce::Time::getMillisecondCounterHiRes() < due)
+                std::this_thread::sleep_for (std::chrono::microseconds (200));
+            io.beginBlock (transport, juce::Time::getMillisecondCounterHiRes(), 256);
+            const auto tps = transport.ticksPerSample();
+            io.subBlock (transport.positionTicks.load(), tps, 256, 0, true);
+            transport.positionTicks.store (transport.positionTicks.load() + 256 * tps);
+        }
+        std::this_thread::sleep_for (std::chrono::milliseconds (100));
+        io.lastStatsMs = 0.0;
+        const auto s = io.stats();
+        report << "sender: sent=" << (juce::int64) s.sent << " dropped=" << (juce::int64) s.dropped << " late mean ms=" << juce::String (s.meanLateMs, 3)
+               << " max ms=" << juce::String (s.maxLateMs, 3) << " (5 s)\n";
+        report << "audio thread per block: mean us=" << juce::String (s.meanBlockUs, 2) << " max us=" << juce::String (s.maxBlockUs, 2) << "\n";
+    }
+    if (input != nullptr)
+    {
+        input->stop();
+        const std::lock_guard<std::mutex> g (in.lock);
+        double sum = 0.0, sum2 = 0.0;
+        const auto n = (int) in.times.size() - 1;
+        for (int i = 0; i < n; ++i)
+        {
+            const auto d = in.times[(std::size_t) i + 1] - in.times[(std::size_t) i];
+            sum += d;
+            sum2 += d * d;
+        }
+        const auto mean = n > 0 ? sum / n : 0.0;
+        report << "input=" << inputName << " clocks=" << (int) in.times.size() << " interval mean ms=" << juce::String (mean, 3)
+               << " sd ms=" << juce::String (n > 0 ? std::sqrt (std::max (0.0, sum2 / n - mean * mean)) : 0.0, 3)
+               << " received bpm=" << juce::String (in.receiver.bpm(), 2) << "\n";
+    }
+    else if (inputName.isNotEmpty())
+        report << "input=" << inputName << " not found\n";
+    return report;
+}
+} // namespace lynx

+ 117 - 0
src/engine/MidiSyncIo.h

@@ -0,0 +1,117 @@
+#pragma once
+
+// MIDI sync devices (REA round 165f, docs/analise/REA_rodada165f-midisync.md): master sync (MIDI clock + SPP, or
+// MTC) to the output devices that have "Send master sync", "Send all notes off" on init and after an export, and
+// "External clock sync" from one input.
+// Threads: the audio thread runs the generators and pushes time-stamped messages into one lock-free queue per output
+// (it never touches a device); a sender thread sends each message when it is due; the MIDI thread feeds the clock
+// receiver; the message thread opens and closes devices.
+
+#include <juce_audio_devices/juce_audio_devices.h>
+
+#include <array>
+#include <atomic>
+#include <memory>
+#include <string>
+
+#include "core/LiveEventQueue.h"
+#include "core/MidiSync.h"
+#include "core/Preferences.h"
+#include "engine/Transport.h"
+
+namespace lynx
+{
+class MidiSyncIo final : private juce::Thread
+{
+public:
+    static constexpr int maxOutputs = 8;
+
+    MidiSyncIo();
+    ~MidiSyncIo() override;
+
+    // message thread: opens the outputs that send sync or notes off, closes the others, sets the clock input. With
+    // `devices` false nothing is opened (tests, --snapshot).
+    // `dryRun`: no device is opened but the sender runs and times every message as if it sent it (--midisync-test).
+    void configure (const prefs::MidiPrefs& prefs, bool devices = true, bool dryRun = false);
+    // message / render thread: CC 123 (All Notes Off) and CC 64 = 0 on the 16 channels of every output with the option
+    void sendAllNotesOff();
+
+    // --- audio thread ---
+    void deviceStarted (double sampleRate, int bufferSize, int outputLatencySamples) noexcept;
+    // Before the block: an external clock's commands and tempo move the transport. `callbackMs` = the callback's
+    // Time::getMillisecondCounterHiRes().
+    void beginBlock (Transport& transport, double callbackMs, int numSamples) noexcept;
+    // Each part of the block (split at loop ends): the master sync messages for it. `offset` = its first sample in
+    // the block.
+    void subBlock (double startTicks, double ticksPerSample, int numSamples, int offset, bool playing) noexcept;
+    bool sending() const noexcept { return anySync.load (std::memory_order_relaxed); }
+
+    // --- MIDI thread: true if the message was the followed clock's (consumed) ---
+    bool handleInput (const juce::String& device, const juce::MidiMessage& m) noexcept;
+
+    // --- UI ---
+    std::string clockStatus() const;             // "No clock" / "Receiving clock 120.0 BPM" (English; the UI translates)
+    double followedBpm() const noexcept;         // the external tempo LYNX plays at now (0 = not following)
+    struct Stats
+    {
+        std::uint64_t sent = 0, dropped = 0;
+        double meanLateMs = 0.0, maxLateMs = 0.0;   // send time − due time, last second
+        double meanBlockUs = 0.0, maxBlockUs = 0.0; // audio-thread cost of the sync per block, last second
+    };
+    Stats stats() const;
+
+    // tests / --midisync-test: the receiver
+    midisync::Receiver& receiver() noexcept { return clockIn; }
+    // LYNX --midisync-test report.txt ["output device"] ["input device"]: the generator → receiver loopback in memory,
+    // then 5 s of simulated audio callbacks (48 kHz, 256 frames) sending MIDI clock through the sender thread (to the
+    // output device, or timed without one), and with an input (a loopback cable / virtual port) the clock received.
+    static juce::String selfTest (const juce::String& outputName, const juce::String& inputName);
+
+private:
+    void run() override;
+
+    struct Timed
+    {
+        double dueMs = 0.0;
+        midisync::Message message;
+    };
+    struct Slot
+    {
+        std::atomic<bool> active { false };  // the audio thread generates for it
+        std::atomic<int> type { 0 };
+        std::atomic<int> offsetMs { 0 };
+        std::atomic<std::uint32_t> generation { 0 };
+        std::uint32_t seenGeneration = 0;    // audio thread
+        midisync::Generator generator;       // audio thread
+        SpscQueue<Timed, 2048> queue;        // audio → sender
+        std::string name;                    // message thread
+        bool notesOff = false, sync = false; // message thread
+        std::unique_ptr<juce::MidiOutput> device; // under outputLock
+    };
+    std::array<Slot, maxOutputs> slots;
+    juce::CriticalSection outputLock;        // the devices (message, sender, render threads; never the audio thread)
+    std::atomic<bool> anySync { false }, dry { false };
+
+    // timing: the device block clock mapped to milliseconds (smoothed: callbacks wake up with jitter)
+    double sampleRate = 44100.0, latencyMs = 0.0;
+    double blockStartMs = 0.0, predictedMs = -1.0;
+    midisync::BlockMessages scratch;
+
+    // external clock
+    midisync::Receiver clockIn;
+    juce::SpinLock clockNameLock;
+    juce::String clockName;                  // under clockNameLock
+    std::atomic<bool> following { false };
+    std::atomic<int> clockOffsetMs { 0 };
+    bool waitingFirstPulse = false;          // audio thread: Start / Continue received, play on the first pulse
+    bool wasFollowing = false;
+    std::atomic<double> appliedBpm { 0.0 };
+
+    // stats (sender thread / audio thread writes, UI reads)
+    std::atomic<std::uint64_t> sentCount { 0 }, droppedCount { 0 };
+    std::atomic<double> lateSum { 0.0 }, lateMax { 0.0 }, blockSum { 0.0 }, blockMax { 0.0 };
+    std::atomic<std::uint64_t> lateN { 0 }, blockN { 0 };
+    mutable Stats lastStats;
+    mutable double lastStatsMs = 0.0;
+};
+} // namespace lynx

+ 5 - 1
src/engine/Transport.h

@@ -18,6 +18,9 @@ struct Transport
     std::atomic<float> metronomeVolume { 1.0f }; // the metronome's volume (0..1.25, 1 = the default click level)
     std::atomic<bool> recording { false };
     std::atomic<double> bpm { 130.0 };
+    // External clock sync (round 165f): > 0 = the tempo LYNX follows from an incoming MIDI clock, over the song's
+    // (written by the audio thread only)
+    std::atomic<double> externalBpm { 0.0 };
     std::atomic<int> beatsPerBar { 4 };
 
     // Playlist time-signature changes for the metronome (song mode): the bar restarts at each
@@ -42,7 +45,8 @@ struct Transport
 
     double ticksPerSample() const noexcept
     {
-        return bpm.load (std::memory_order_relaxed) * ppq / (60.0 * sampleRate.load (std::memory_order_relaxed));
+        const auto external = externalBpm.load (std::memory_order_relaxed);
+        return (external > 0.0 ? external : bpm.load (std::memory_order_relaxed)) * ppq / (60.0 * sampleRate.load (std::memory_order_relaxed));
     }
 
     double positionInBeats() const noexcept

+ 109 - 1
src/ui/I18nData.h

@@ -15330,6 +15330,114 @@ inline constexpr unsigned char ptBR[] = {
 32, 34, 69, 115, 112, 101, 115, 115, 117, 114, 97, 34, 10, 34, 66, 101, 97, 116, 32, 116, 104, 114, 101, 115,
 104, 111, 108, 100, 34, 32, 61, 32, 34, 76, 105, 109, 105, 97, 114, 32, 100, 97, 32, 98, 97, 116, 105, 100,
 97, 34, 10, 34, 72, 117, 101, 32, 115, 104, 105, 102, 116, 34, 32, 61, 32, 34, 82, 111, 116, 97, 195, 167,
-195, 163, 111, 32, 100, 101, 32, 109, 97, 116, 105, 122, 34, 10,
+195, 163, 111, 32, 100, 101, 32, 109, 97, 116, 105, 122, 34, 10, 10, 35, 32, 45, 45, 45, 32, 83, 101, 116,
+116, 105, 110, 103, 115, 32, 226, 128, 186, 32, 77, 73, 68, 73, 58, 32, 109, 97, 115, 116, 101, 114, 32, 115,
+121, 110, 99, 32, 97, 110, 100, 32, 101, 120, 116, 101, 114, 110, 97, 108, 32, 99, 108, 111, 99, 107, 32, 40,
+114, 111, 117, 110, 100, 32, 49, 54, 53, 102, 41, 10, 34, 79, 117, 116, 112, 117, 116, 32, 100, 101, 118, 105,
+99, 101, 115, 34, 32, 61, 32, 34, 68, 105, 115, 112, 111, 115, 105, 116, 105, 118, 111, 115, 32, 100, 101, 32,
+115, 97, 195, 173, 100, 97, 34, 10, 34, 78, 111, 32, 77, 73, 68, 73, 32, 111, 117, 116, 112, 117, 116, 32,
+100, 101, 118, 105, 99, 101, 115, 32, 102, 111, 117, 110, 100, 46, 34, 32, 61, 32, 34, 78, 101, 110, 104, 117,
+109, 32, 100, 105, 115, 112, 111, 115, 105, 116, 105, 118, 111, 32, 100, 101, 32, 115, 97, 195, 173, 100, 97, 32,
+77, 73, 68, 73, 32, 101, 110, 99, 111, 110, 116, 114, 97, 100, 111, 46, 34, 10, 34, 83, 101, 110, 100, 32,
+109, 97, 115, 116, 101, 114, 32, 115, 121, 110, 99, 32, 100, 114, 105, 118, 101, 115, 32, 100, 114, 117, 109, 32,
+109, 97, 99, 104, 105, 110, 101, 115, 44, 32, 115, 121, 110, 116, 104, 115, 32, 97, 110, 100, 32, 111, 116, 104,
+101, 114, 32, 115, 111, 102, 116, 119, 97, 114, 101, 32, 102, 114, 111, 109, 32, 76, 89, 78, 88, 39, 115, 32,
+116, 114, 97, 110, 115, 112, 111, 114, 116, 58, 32, 77, 73, 68, 73, 32, 99, 108, 111, 99, 107, 32, 119, 105,
+116, 104, 32, 83, 111, 110, 103, 32, 80, 111, 115, 105, 116, 105, 111, 110, 32, 80, 111, 105, 110, 116, 101, 114,
+44, 32, 111, 114, 32, 77, 73, 68, 73, 32, 84, 105, 109, 101, 32, 67, 111, 100, 101, 46, 34, 32, 61, 32,
+34, 69, 110, 118, 105, 97, 114, 32, 115, 105, 110, 99, 114, 111, 110, 105, 122, 97, 195, 167, 195, 163, 111, 32,
+109, 101, 115, 116, 114, 101, 32, 99, 111, 109, 97, 110, 100, 97, 32, 98, 97, 116, 101, 114, 105, 97, 115, 32,
+101, 108, 101, 116, 114, 195, 180, 110, 105, 99, 97, 115, 44, 32, 115, 105, 110, 116, 101, 116, 105, 122, 97, 100,
+111, 114, 101, 115, 32, 101, 32, 111, 117, 116, 114, 111, 115, 32, 112, 114, 111, 103, 114, 97, 109, 97, 115, 32,
+112, 101, 108, 111, 32, 116, 114, 97, 110, 115, 112, 111, 114, 116, 101, 32, 100, 111, 32, 76, 89, 78, 88, 58,
+32, 77, 73, 68, 73, 32, 99, 108, 111, 99, 107, 32, 99, 111, 109, 32, 83, 111, 110, 103, 32, 80, 111, 115,
+105, 116, 105, 111, 110, 32, 80, 111, 105, 110, 116, 101, 114, 44, 32, 111, 117, 32, 77, 73, 68, 73, 32, 84,
+105, 109, 101, 32, 67, 111, 100, 101, 46, 34, 10, 34, 83, 101, 110, 100, 32, 109, 97, 115, 116, 101, 114, 32,
+115, 121, 110, 99, 34, 32, 61, 32, 34, 69, 110, 118, 105, 97, 114, 32, 115, 105, 110, 99, 114, 111, 110, 105,
+122, 97, 195, 167, 195, 163, 111, 32, 109, 101, 115, 116, 114, 101, 34, 10, 34, 83, 101, 110, 100, 32, 109, 97,
+115, 116, 101, 114, 32, 115, 121, 110, 99, 104, 114, 111, 110, 105, 122, 97, 116, 105, 111, 110, 32, 116, 111, 32,
+116, 104, 105, 115, 32, 100, 101, 118, 105, 99, 101, 34, 32, 61, 32, 34, 69, 110, 118, 105, 97, 32, 97, 32,
+115, 105, 110, 99, 114, 111, 110, 105, 122, 97, 195, 167, 195, 163, 111, 32, 109, 101, 115, 116, 114, 101, 32, 112,
+97, 114, 97, 32, 101, 115, 116, 101, 32, 100, 105, 115, 112, 111, 115, 105, 116, 105, 118, 111, 34, 10, 34, 77,
+73, 68, 73, 32, 99, 108, 111, 99, 107, 58, 32, 50, 52, 32, 112, 117, 108, 115, 101, 115, 32, 112, 101, 114,
+32, 113, 117, 97, 114, 116, 101, 114, 32, 110, 111, 116, 101, 44, 32, 83, 116, 97, 114, 116, 32, 47, 32, 67,
+111, 110, 116, 105, 110, 117, 101, 32, 47, 32, 83, 116, 111, 112, 32, 97, 110, 100, 32, 83, 111, 110, 103, 32,
+80, 111, 115, 105, 116, 105, 111, 110, 32, 80, 111, 105, 110, 116, 101, 114, 46, 32, 77, 84, 67, 58, 32, 77,
+73, 68, 73, 32, 84, 105, 109, 101, 32, 67, 111, 100, 101, 32, 113, 117, 97, 114, 116, 101, 114, 32, 102, 114,
+97, 109, 101, 115, 32, 97, 110, 100, 32, 97, 32, 102, 117, 108, 108, 32, 102, 114, 97, 109, 101, 32, 119, 104,
+101, 110, 32, 116, 104, 101, 32, 112, 111, 115, 105, 116, 105, 111, 110, 32, 109, 111, 118, 101, 115, 46, 34, 32,
+61, 32, 34, 77, 73, 68, 73, 32, 99, 108, 111, 99, 107, 58, 32, 50, 52, 32, 112, 117, 108, 115, 111, 115,
+32, 112, 111, 114, 32, 115, 101, 109, 195, 173, 110, 105, 109, 97, 44, 32, 83, 116, 97, 114, 116, 32, 47, 32,
+67, 111, 110, 116, 105, 110, 117, 101, 32, 47, 32, 83, 116, 111, 112, 32, 101, 32, 83, 111, 110, 103, 32, 80,
+111, 115, 105, 116, 105, 111, 110, 32, 80, 111, 105, 110, 116, 101, 114, 46, 32, 77, 84, 67, 58, 32, 113, 117,
+97, 114, 116, 101, 114, 32, 102, 114, 97, 109, 101, 115, 32, 100, 101, 32, 77, 73, 68, 73, 32, 84, 105, 109,
+101, 32, 67, 111, 100, 101, 32, 101, 32, 117, 109, 32, 102, 117, 108, 108, 32, 102, 114, 97, 109, 101, 32, 113,
+117, 97, 110, 100, 111, 32, 97, 32, 112, 111, 115, 105, 195, 167, 195, 163, 111, 32, 109, 117, 100, 97, 46, 34,
+10, 34, 77, 73, 68, 73, 32, 99, 108, 111, 99, 107, 34, 32, 61, 32, 34, 77, 73, 68, 73, 32, 99, 108,
+111, 99, 107, 34, 10, 34, 77, 84, 67, 32, 50, 52, 32, 102, 112, 115, 34, 32, 61, 32, 34, 77, 84, 67,
+32, 50, 52, 32, 102, 112, 115, 34, 10, 34, 77, 84, 67, 32, 50, 53, 32, 102, 112, 115, 34, 32, 61, 32,
+34, 77, 84, 67, 32, 50, 53, 32, 102, 112, 115, 34, 10, 34, 77, 84, 67, 32, 51, 48, 32, 102, 112, 115,
+32, 40, 100, 114, 111, 112, 41, 34, 32, 61, 32, 34, 77, 84, 67, 32, 51, 48, 32, 102, 112, 115, 32, 40,
+100, 114, 111, 112, 45, 102, 114, 97, 109, 101, 41, 34, 10, 34, 77, 84, 67, 32, 51, 48, 32, 102, 112, 115,
+32, 40, 110, 111, 110, 45, 100, 114, 111, 112, 41, 34, 32, 61, 32, 34, 77, 84, 67, 32, 51, 48, 32, 102,
+112, 115, 32, 40, 110, 111, 110, 45, 100, 114, 111, 112, 41, 34, 10, 34, 77, 84, 67, 32, 50, 57, 46, 57,
+55, 32, 102, 112, 115, 32, 40, 100, 114, 111, 112, 41, 34, 32, 61, 32, 34, 77, 84, 67, 32, 50, 57, 44,
+57, 55, 32, 102, 112, 115, 32, 40, 100, 114, 111, 112, 45, 102, 114, 97, 109, 101, 41, 34, 10, 34, 77, 84,
+67, 32, 50, 57, 46, 57, 55, 32, 102, 112, 115, 32, 40, 110, 111, 110, 45, 100, 114, 111, 112, 41, 34, 32,
+61, 32, 34, 77, 84, 67, 32, 50, 57, 44, 57, 55, 32, 102, 112, 115, 32, 40, 110, 111, 110, 45, 100, 114,
+111, 112, 41, 34, 10, 34, 79, 102, 102, 115, 101, 116, 32, 40, 109, 115, 41, 34, 32, 61, 32, 34, 68, 101,
+115, 108, 111, 99, 97, 109, 101, 110, 116, 111, 32, 40, 109, 115, 41, 34, 10, 34, 77, 97, 115, 116, 101, 114,
+32, 115, 121, 110, 99, 32, 111, 102, 102, 115, 101, 116, 32, 40, 109, 105, 108, 108, 105, 115, 101, 99, 111, 110,
+100, 115, 41, 58, 32, 112, 111, 115, 105, 116, 105, 118, 101, 32, 115, 101, 110, 100, 115, 32, 116, 104, 101, 32,
+115, 121, 110, 99, 32, 108, 97, 116, 101, 114, 44, 32, 110, 101, 103, 97, 116, 105, 118, 101, 32, 101, 97, 114,
+108, 105, 101, 114, 34, 32, 61, 32, 34, 68, 101, 115, 108, 111, 99, 97, 109, 101, 110, 116, 111, 32, 100, 97,
+32, 115, 105, 110, 99, 114, 111, 110, 105, 122, 97, 195, 167, 195, 163, 111, 32, 109, 101, 115, 116, 114, 101, 32,
+40, 109, 105, 108, 105, 115, 115, 101, 103, 117, 110, 100, 111, 115, 41, 58, 32, 112, 111, 115, 105, 116, 105, 118,
+111, 32, 101, 110, 118, 105, 97, 32, 109, 97, 105, 115, 32, 116, 97, 114, 100, 101, 44, 32, 110, 101, 103, 97,
+116, 105, 118, 111, 32, 109, 97, 105, 115, 32, 99, 101, 100, 111, 34, 10, 34, 83, 101, 110, 100, 32, 97, 108,
+108, 32, 110, 111, 116, 101, 115, 32, 111, 102, 102, 34, 32, 61, 32, 34, 69, 110, 118, 105, 97, 114, 32, 97,
+108, 108, 32, 110, 111, 116, 101, 115, 32, 111, 102, 102, 34, 10, 34, 83, 101, 110, 100, 32, 97, 108, 108, 32,
+110, 111, 116, 101, 115, 32, 111, 102, 102, 32, 116, 111, 32, 116, 104, 105, 115, 32, 100, 101, 118, 105, 99, 101,
+32, 111, 110, 32, 105, 110, 105, 116, 32, 97, 110, 100, 32, 97, 102, 116, 101, 114, 32, 97, 110, 32, 101, 120,
+112, 111, 114, 116, 34, 32, 61, 32, 34, 69, 110, 118, 105, 97, 32, 97, 108, 108, 32, 110, 111, 116, 101, 115,
+32, 111, 102, 102, 32, 97, 32, 101, 115, 116, 101, 32, 100, 105, 115, 112, 111, 115, 105, 116, 105, 118, 111, 32,
+97, 111, 32, 105, 110, 105, 99, 105, 97, 114, 32, 101, 32, 100, 101, 112, 111, 105, 115, 32, 100, 101, 32, 117,
+109, 97, 32, 101, 120, 112, 111, 114, 116, 97, 195, 167, 195, 163, 111, 34, 10, 34, 69, 120, 116, 101, 114, 110,
+97, 108, 32, 115, 121, 110, 99, 34, 32, 61, 32, 34, 83, 105, 110, 99, 114, 111, 110, 105, 122, 97, 195, 167,
+195, 163, 111, 32, 101, 120, 116, 101, 114, 110, 97, 34, 10, 34, 69, 120, 116, 101, 114, 110, 97, 108, 32, 99,
+108, 111, 99, 107, 32, 115, 121, 110, 99, 34, 32, 61, 32, 34, 83, 105, 110, 99, 114, 111, 110, 105, 122, 97,
+114, 32, 99, 111, 109, 32, 99, 108, 111, 99, 107, 32, 101, 120, 116, 101, 114, 110, 111, 34, 10, 34, 76, 89,
+78, 88, 32, 102, 111, 108, 108, 111, 119, 115, 32, 116, 104, 101, 32, 77, 73, 68, 73, 32, 99, 108, 111, 99,
+107, 32, 111, 102, 32, 116, 104, 105, 115, 32, 105, 110, 112, 117, 116, 58, 32, 105, 116, 115, 32, 116, 101, 109,
+112, 111, 44, 32, 83, 116, 97, 114, 116, 32, 47, 32, 67, 111, 110, 116, 105, 110, 117, 101, 32, 47, 32, 83,
+116, 111, 112, 32, 97, 110, 100, 32, 83, 111, 110, 103, 32, 80, 111, 115, 105, 116, 105, 111, 110, 32, 80, 111,
+105, 110, 116, 101, 114, 34, 32, 61, 32, 34, 79, 32, 76, 89, 78, 88, 32, 115, 101, 103, 117, 101, 32, 111,
+32, 77, 73, 68, 73, 32, 99, 108, 111, 99, 107, 32, 100, 101, 115, 116, 97, 32, 101, 110, 116, 114, 97, 100,
+97, 58, 32, 111, 32, 97, 110, 100, 97, 109, 101, 110, 116, 111, 44, 32, 83, 116, 97, 114, 116, 32, 47, 32,
+67, 111, 110, 116, 105, 110, 117, 101, 32, 47, 32, 83, 116, 111, 112, 32, 101, 32, 83, 111, 110, 103, 32, 80,
+111, 115, 105, 116, 105, 111, 110, 32, 80, 111, 105, 110, 116, 101, 114, 34, 10, 34, 69, 120, 116, 101, 114, 110,
+97, 108, 32, 115, 121, 110, 99, 32, 111, 102, 102, 115, 101, 116, 32, 40, 109, 105, 108, 108, 105, 115, 101, 99,
+111, 110, 100, 115, 41, 34, 32, 61, 32, 34, 68, 101, 115, 108, 111, 99, 97, 109, 101, 110, 116, 111, 32, 100,
+97, 32, 115, 105, 110, 99, 114, 111, 110, 105, 122, 97, 195, 167, 195, 163, 111, 32, 101, 120, 116, 101, 114, 110,
+97, 32, 40, 109, 105, 108, 105, 115, 115, 101, 103, 117, 110, 100, 111, 115, 41, 34, 10, 34, 80, 111, 115, 105,
+116, 105, 118, 101, 32, 112, 108, 97, 121, 115, 32, 76, 89, 78, 88, 32, 108, 97, 116, 101, 114, 32, 116, 104,
+97, 110, 32, 116, 104, 101, 32, 99, 108, 111, 99, 107, 44, 32, 110, 101, 103, 97, 116, 105, 118, 101, 32, 101,
+97, 114, 108, 105, 101, 114, 34, 32, 61, 32, 34, 80, 111, 115, 105, 116, 105, 118, 111, 32, 116, 111, 99, 97,
+32, 111, 32, 76, 89, 78, 88, 32, 109, 97, 105, 115, 32, 116, 97, 114, 100, 101, 32, 113, 117, 101, 32, 111,
+32, 99, 108, 111, 99, 107, 44, 32, 110, 101, 103, 97, 116, 105, 118, 111, 32, 109, 97, 105, 115, 32, 99, 101,
+100, 111, 34, 10, 34, 78, 111, 32, 99, 108, 111, 99, 107, 34, 32, 61, 32, 34, 83, 101, 109, 32, 99, 108,
+111, 99, 107, 34, 10, 34, 67, 108, 111, 99, 107, 32, 105, 115, 32, 116, 111, 111, 32, 102, 97, 115, 116, 33,
+34, 32, 61, 32, 34, 67, 108, 111, 99, 107, 32, 114, 195, 161, 112, 105, 100, 111, 32, 100, 101, 109, 97, 105,
+115, 33, 34, 10, 34, 82, 101, 99, 101, 105, 118, 105, 110, 103, 32, 99, 108, 111, 99, 107, 32, 123, 48, 125,
+32, 66, 80, 77, 34, 32, 61, 32, 34, 82, 101, 99, 101, 98, 101, 110, 100, 111, 32, 99, 108, 111, 99, 107,
+32, 97, 32, 123, 48, 125, 32, 66, 80, 77, 34, 10, 34, 112, 108, 97, 121, 105, 110, 103, 34, 32, 61, 32,
+34, 116, 111, 99, 97, 110, 100, 111, 34, 10, 34, 84, 104, 101, 32, 105, 110, 112, 117, 116, 32, 109, 117, 115,
+116, 32, 98, 101, 32, 111, 110, 32, 105, 110, 32, 73, 110, 112, 117, 116, 32, 100, 101, 118, 105, 99, 101, 115,
+32, 97, 98, 111, 118, 101, 46, 32, 83, 111, 110, 103, 32, 116, 105, 109, 101, 32, 119, 105, 108, 108, 32, 109,
+97, 116, 99, 104, 32, 116, 104, 101, 32, 99, 108, 111, 99, 107, 46, 34, 32, 61, 32, 34, 65, 32, 101, 110,
+116, 114, 97, 100, 97, 32, 112, 114, 101, 99, 105, 115, 97, 32, 101, 115, 116, 97, 114, 32, 108, 105, 103, 97,
+100, 97, 32, 101, 109, 32, 68, 105, 115, 112, 111, 115, 105, 116, 105, 118, 111, 115, 32, 100, 101, 32, 101, 110,
+116, 114, 97, 100, 97, 32, 97, 99, 105, 109, 97, 46, 32, 79, 32, 116, 101, 109, 112, 111, 32, 100, 97, 32,
+109, 195, 186, 115, 105, 99, 97, 32, 115, 101, 103, 117, 101, 32, 111, 32, 99, 108, 111, 99, 107, 46, 34, 10,
 };
 } // namespace lynx::i18n::data

+ 222 - 2
src/ui/SettingsPages.cpp

@@ -937,8 +937,103 @@ private:
     juce::ComboBox channel, plays;
 };
 
+// One output device (FL's Options › MIDI "Output" panel, round 165f): master sync (MIDI clock or MTC) with its
+// offset, and all notes off on init and after an export.
+class MidiOutputRow final : public juce::Component
+{
+public:
+    MidiOutputRow (const juce::String& deviceName, const prefs::MidiOutputPrefs& p, std::function<void (const prefs::MidiOutputPrefs&)> changed)
+        : prefsNow (p), onChange (std::move (changed))
+    {
+        name.setText (deviceName, juce::dontSendNotification);
+        name.setFont (theme::font (theme::type::body));
+        name.setColour (juce::Label::textColourId, theme::colour::textPrimary);
+        addAndMakeVisible (name);
+
+        sync.setButtonText (tr ("Send master sync"));
+        sync.setTooltip (tr ("Send master synchronization to this device"));
+        sync.setToggleState (p.masterSync, juce::dontSendNotification);
+        sync.onClick = [this] {
+            prefsNow.masterSync = sync.getToggleState();
+            update();
+        };
+        for (int t = 0; t < midisync::syncTypeCount; ++t)
+            type.addItem (tr (midisync::syncTypeName ((midisync::SyncType) t)), t + 1);
+        type.setTooltip (tr ("MIDI clock: 24 pulses per quarter note, Start / Continue / Stop and Song Position Pointer. "
+                             "MTC: MIDI Time Code quarter frames and a full frame when the position moves."));
+        type.setSelectedId ((int) midisync::syncTypeFromKey (p.syncType) + 1, juce::dontSendNotification);
+        type.onChange = [this] {
+            prefsNow.syncType = midisync::syncTypeKey ((midisync::SyncType) (type.getSelectedId() - 1));
+            update();
+        };
+        styleCombo (type);
+        offsetLabel.setText (tr ("Offset (ms)"), juce::dontSendNotification);
+        offsetLabel.setFont (theme::font (theme::type::small));
+        offsetLabel.setColour (juce::Label::textColourId, theme::colour::textSecondary);
+        offset.setSliderStyle (juce::Slider::IncDecButtons);
+        offset.setTextBoxStyle (juce::Slider::TextBoxLeft, false, 56, 24);
+        offset.setRange (-1000.0, 1000.0, 1.0);
+        offset.setValue (p.offsetMs, juce::dontSendNotification);
+        offset.setTooltip (tr ("Master sync offset (milliseconds): positive sends the sync later, negative earlier"));
+        offset.setDoubleClickReturnValue (true, 0.0);
+        offset.onValueChange = [this] {
+            prefsNow.offsetMs = (int) offset.getValue();
+            update();
+        };
+        notesOff.setButtonText (tr ("Send all notes off"));
+        notesOff.setTooltip (tr ("Send all notes off to this device on init and after an export"));
+        notesOff.setToggleState (p.allNotesOff, juce::dontSendNotification);
+        notesOff.onClick = [this] {
+            prefsNow.allNotesOff = notesOff.getToggleState();
+            update();
+        };
+        for (auto* c : std::initializer_list<juce::Component*> { &sync, &type, &offsetLabel, &offset, &notesOff })
+            addAndMakeVisible (c);
+        update (false);
+    }
+
+    void resized() override
+    {
+        auto r = getLocalBounds().reduced (8, 4);
+        auto top = r.removeFromTop (24);
+        notesOff.setBounds (top.removeFromRight (170));
+        name.setBounds (top);
+        r.removeFromTop (4);
+        auto bottom = r.removeFromTop (26);
+        sync.setBounds (bottom.removeFromLeft (150));
+        bottom.removeFromLeft (8);
+        type.setBounds (bottom.removeFromLeft (190));
+        bottom.removeFromLeft (12);
+        offsetLabel.setBounds (bottom.removeFromLeft (76));
+        offset.setBounds (bottom.removeFromLeft (110));
+    }
+
+    void paint (juce::Graphics& g) override
+    {
+        g.setColour (theme::colour::bg1);
+        g.fillRoundedRectangle (getLocalBounds().toFloat(), theme::radius::md);
+    }
+
+private:
+    void update (bool notify = true)
+    {
+        type.setEnabled (prefsNow.masterSync);
+        offset.setEnabled (prefsNow.masterSync);
+        if (notify && onChange)
+            onChange (prefsNow);
+    }
+
+    prefs::MidiOutputPrefs prefsNow;
+    std::function<void (const prefs::MidiOutputPrefs&)> onChange;
+    juce::Label name, offsetLabel;
+    juce::ToggleButton sync, notesOff;
+    juce::ComboBox type;
+    juce::Slider offset;
+};
+
 class MidiPage final : public ScrollingPage,
                        private juce::ChangeListener,
+                       private juce::Timer,
                        private juce::ListBoxModel
 {
 public:
@@ -946,8 +1041,41 @@ public:
     {
         for (auto* c : std::initializer_list<juce::Component*> { &inputsTitle, &notesTitle, &controllersTitle, &inputsNote, &refresh, &noDevices,
                                                                  &velocityLabel, &velocityBox, &velocityNote, &typeLabel, &typeValue, &pickup,
-                                                                 &pickupNote, &linksLabel, &links, &removeLink, &removeAll })
+                                                                 &pickupNote, &linksLabel, &links, &removeLink, &removeAll, &outputsTitle,
+                                                                 &outputsNote, &noOutputs, &syncTitle, &clockLabel, &clockBox, &clockOffsetLabel,
+                                                                 &clockOffset, &clockStatusLabel, &clockStatus, &clockNote })
             add (*c);
+        styleNote (outputsNote, tr ("Send master sync drives drum machines, synths and other software from LYNX's transport: MIDI clock "
+                                    "with Song Position Pointer, or MIDI Time Code."));
+        styleLabel (noOutputs, tr ("No MIDI output devices found."));
+        styleLabel (clockLabel, tr ("External clock sync"));
+        clockBox.setTooltip (tr ("LYNX follows the MIDI clock of this input: its tempo, Start / Continue / Stop and Song Position Pointer"));
+        clockBox.onChange = [this] {
+            if (loading)
+                return;
+            auto p = engine.getMidiPrefs();
+            const auto id = clockBox.getSelectedId();
+            p.clockInput = id > 1 && id - 2 < clockInputs.size() ? clockInputs[id - 2].toStdString() : std::string();
+            set (p);
+        };
+        styleCombo (clockBox);
+        styleLabel (clockOffsetLabel, tr ("External sync offset (milliseconds)"));
+        clockOffset.setSliderStyle (juce::Slider::IncDecButtons);
+        clockOffset.setTextBoxStyle (juce::Slider::TextBoxLeft, false, 80, 24);
+        clockOffset.setRange (-1000.0, 1000.0, 1.0);
+        clockOffset.setDoubleClickReturnValue (true, 0.0);
+        clockOffset.setTooltip (tr ("Positive plays LYNX later than the clock, negative earlier"));
+        clockOffset.onValueChange = [this] {
+            if (loading)
+                return;
+            auto p = engine.getMidiPrefs();
+            p.clockOffsetMs = (int) clockOffset.getValue();
+            set (p);
+        };
+        styleLabel (clockStatusLabel, tr ("Status"));
+        styleLabel (clockStatus, tr ("No clock"), false);
+        styleNote (clockNote, tr ("The input must be on in Input devices above. Song time will match the clock."));
+        startTimerHz (4);
         styleNote (inputsNote, tr ("Each input device can be turned off, listen to one MIDI channel only and play a fixed channel of the "
                                    "Channel Rack instead of the selected ones."));
         styleLabel (noDevices, tr ("No MIDI input devices found. Connect one and refresh the list."));
@@ -1004,6 +1132,15 @@ public:
         {
             // --snapshot: devices of a typical setup, and two links
             sampleDevices = { "Arturia KeyLab 49", "Akai MPD218" };
+            sampleOutputs = { "Roland TR-8S", "Korg volca sample" };
+            auto p = engine.getMidiPrefs();
+            prefs::MidiOutputPrefs drums;
+            drums.name = "Roland TR-8S";
+            drums.masterSync = true;
+            drums.allNotesOff = true;
+            p.setOutput (drums);
+            p.clockInput = "Akai MPD218";
+            engine.setMidiPrefs (p, false);
             engine.editSong ([] (Song& s) {
                 AutomationTarget volume;
                 volume.kind = AutomationTargetKind::mixerVolume;
@@ -1020,7 +1157,11 @@ public:
         load();
     }
 
-    ~MidiPage() override { engine.removeChangeListener (this); }
+    ~MidiPage() override
+    {
+        stopTimer();
+        engine.removeChangeListener (this);
+    }
 
 private:
     int layout (int width) override
@@ -1034,6 +1175,19 @@ private:
             row->setBounds (r.full (34).translated (0, -4));
         refresh.setBounds (r.full().removeFromLeft (150));
 
+        r.section (outputsTitle);
+        outputsNote.setBounds (r.full (32).translated (0, -4));
+        if (outputRows.empty())
+            noOutputs.setBounds (r.full (24));
+        for (auto& row : outputRows)
+            row->setBounds (r.full (66).translated (0, -4));
+
+        r.section (syncTitle);
+        clockBox.setBounds (r.row (clockLabel, 300));
+        clockOffset.setBounds (r.row (clockOffsetLabel, 200));
+        clockStatus.setBounds (r.row (clockStatusLabel, 0));
+        clockNote.setBounds (r.indented (16).translated (0, -3));
+
         r.section (notesTitle);
         velocityBox.setBounds (r.row (velocityLabel, 300));
         velocityNote.setBounds (r.indented (16).translated (0, -3));
@@ -1074,6 +1228,14 @@ private:
         const auto& p = engine.getMidiPrefs();
         velocityBox.setSelectedId ((int) p.velocity + 1, juce::dontSendNotification);
         pickup.setToggleState (p.pickup, juce::dontSendNotification);
+        {
+            auto id = 1;
+            for (int i = 0; i < clockInputs.size(); ++i)
+                if (clockInputs[i].toStdString() == p.clockInput)
+                    id = i + 2;
+            clockBox.setSelectedId (id, juce::dontSendNotification);
+        }
+        clockOffset.setValue (p.clockOffsetMs, juce::dontSendNotification);
         links.updateContent();
         links.repaint();
         removeLink.setEnabled (links.getSelectedRow() >= 0);
@@ -1109,9 +1271,61 @@ private:
             rows.push_back (std::move (row));
         }
         noDevices.setVisible (rows.empty());
+
+        // the clock input list: off, then the inputs (a saved one missing now stays listed)
+        clockInputs = names;
+        if (const auto saved = juce::String::fromUTF8 (engine.getMidiPrefs().clockInput.c_str()); saved.isNotEmpty() && ! clockInputs.contains (saved))
+            clockInputs.add (saved);
+        clockBox.clear (juce::dontSendNotification);
+        clockBox.addItem (tr ("Off"), 1);
+        for (int i = 0; i < clockInputs.size(); ++i)
+            clockBox.addItem (clockInputs[i], i + 2);
+
+        outputRows.clear();
+        juce::StringArray outputs;
+        if (persistent)
+            for (const auto& d : juce::MidiOutput::getAvailableDevices())
+                outputs.add (d.name);
+        else
+            outputs = sampleOutputs;
+        for (const auto& name : outputs)
+        {
+            auto row = std::make_unique<MidiOutputRow> (name, engine.getMidiPrefs().output (name.toStdString()), [this] (const prefs::MidiOutputPrefs& out) {
+                auto p = engine.getMidiPrefs();
+                p.setOutput (out);
+                set (p);
+            });
+            add (*row);
+            outputRows.push_back (std::move (row));
+        }
+        noOutputs.setVisible (outputRows.empty());
+        load();
         resized();
     }
 
+    void timerCallback() override
+    {
+        const auto& p = engine.getMidiPrefs();
+        juce::String text;
+        if (p.clockInput.empty())
+            text = tr ("Off");
+        else if (! persistent)
+            text = tr ("Receiving clock {0} BPM", { "120.0" }); // --snapshot
+        else
+        {
+            const auto status = engine.getMidiSync().clockStatus();
+            if (status == "No clock")
+                text = tr ("No clock");
+            else if (status.rfind ("Clock is too fast", 0) == 0)
+                text = tr ("Clock is too fast!");
+            else
+                text = tr ("Receiving clock {0} BPM", { juce::String (engine.getMidiSync().receiver().bpm(), 1) })
+                       + (engine.getMidiSync().receiver().running() ? ", " + tr ("playing") : juce::String());
+        }
+        if (clockStatus.getText() != text)
+            clockStatus.setText (text, juce::dontSendNotification);
+    }
+
     // links list
     int getNumRows() override { return juce::jmax (1, linkRows()); }
 
@@ -1162,6 +1376,12 @@ private:
     std::size_t channelCount = 0;
     juce::StringArray sampleDevices;
     std::vector<std::unique_ptr<MidiInputRow>> rows;
+    std::vector<std::unique_ptr<MidiOutputRow>> outputRows;
+    juce::StringArray sampleOutputs, clockInputs;
+    SectionTitle outputsTitle { tr ("Output devices") }, syncTitle { tr ("External sync") };
+    juce::Label outputsNote, noOutputs, clockLabel, clockOffsetLabel, clockStatusLabel, clockStatus, clockNote;
+    juce::ComboBox clockBox;
+    juce::Slider clockOffset;
     SectionTitle inputsTitle { tr ("Input devices") }, notesTitle { tr ("Notes") }, controllersTitle { tr ("Controllers") };
     juce::Label inputsNote, noDevices, velocityLabel, velocityNote, typeLabel, typeValue, pickupNote, linksLabel;
     juce::TextButton refresh { tr ("Refresh device list") }, removeLink { tr ("Remove link") }, removeAll { tr ("Remove all") };

+ 320 - 0
tests/MidiSync165Tests.inc

@@ -0,0 +1,320 @@
+// Round 165f (rea165-midisync): MIDI clock / MTC master sync and external clock sync
+// (docs/analise/REA_rodada165f-midisync.md)
+
+namespace midisync165
+{
+using namespace lynx::midisync;
+
+// runs the generator over `blocks` blocks of `n` samples at `bpm`, starting at `startTicks`
+struct Run
+{
+    std::vector<std::pair<std::int64_t, Message>> sent; // absolute sample, message
+};
+
+inline void play (Generator& g, Run& run, double& ticks, std::int64_t& sample, int blocks, int n, double bpm, double rate = 48000.0,
+                  bool playing = true, bool jumped = false)
+{
+    for (int b = 0; b < blocks; ++b)
+    {
+        Block block;
+        block.startTicks = ticks;
+        block.ticksPerSample = bpm * 960.0 / (60.0 * rate);
+        block.sampleRate = rate;
+        block.numSamples = n;
+        block.playing = playing;
+        block.jumped = jumped && b == 0;
+        BlockMessages out;
+        g.process (block, ticks / (block.ticksPerSample * rate), out);
+        for (int i = 0; i < out.count; ++i)
+            run.sent.push_back ({ sample + out.items[(std::size_t) i].sample, out.items[(std::size_t) i] });
+        if (playing)
+            ticks += n * block.ticksPerSample;
+        sample += n;
+    }
+}
+
+inline int countStatus (const Run& r, std::uint8_t status)
+{
+    return (int) std::count_if (r.sent.begin(), r.sent.end(), [status] (const auto& m) { return m.second.bytes[0] == status; });
+}
+} // namespace midisync165
+
+TEST (midisync165_clock_pulses_land_on_their_samples)
+{
+    using namespace midisync165;
+    Generator g;
+    Run run;
+    double ticks = 0.0;
+    std::int64_t sample = 0;
+    // 120 BPM at 48 kHz: a pulse every 48000 * 0.5 / 24 = 1000 samples; blocks of 333 split pulses everywhere
+    play (g, run, ticks, sample, 300, 333, 120.0);
+    CHECK (! run.sent.empty() && run.sent[0].second.bytes[0] == 0xfa && run.sent[0].first == 0);
+    std::vector<std::int64_t> pulses;
+    for (const auto& [at, m] : run.sent)
+        if (m.bytes[0] == 0xf8)
+            pulses.push_back (at);
+    CHECK (pulses.size() == 100); // 99 900 samples: pulses at 0, 1000 … 99 000
+    for (std::size_t i = 0; i < pulses.size(); ++i)
+        CHECK (pulses[i] == (std::int64_t) i * 1000);
+    // stop: one Stop, then nothing
+    play (g, run, ticks, sample, 10, 333, 120.0, 48000.0, false);
+    CHECK (countStatus (run, 0xfc) == 1);
+    CHECK (run.sent.back().second.bytes[0] == 0xfc);
+}
+
+TEST (midisync165_clock_follows_tempo_changes)
+{
+    using namespace midisync165;
+    Generator g;
+    Run run;
+    double ticks = 0.0;
+    std::int64_t sample = 0;
+    play (g, run, ticks, sample, 48, 1000, 120.0); // 1 s at 120: 48 pulses, 1000 samples apart
+    const auto before = (std::size_t) countStatus (run, 0xf8);
+    play (g, run, ticks, sample, 48, 1000, 60.0); // 1 s at 60: 24 pulses, 2000 samples apart
+    CHECK (before == 48);
+    CHECK (countStatus (run, 0xf8) == 72);
+    std::vector<std::int64_t> pulses;
+    for (const auto& [at, m] : run.sent)
+        if (m.bytes[0] == 0xf8)
+            pulses.push_back (at);
+    CHECK (pulses[48] == 48000 && pulses[49] == 50000 && pulses.back() == 94000);
+}
+
+TEST (midisync165_spp_and_continue_on_start_elsewhere_and_jumps)
+{
+    using namespace midisync165;
+    CHECK (sppFor (0.0) == 0 && sppFor (240.0) == 1 && sppFor (241.0) == 2 && sppFor (3840.0) == 16);
+    Generator g;
+    Run run;
+    double ticks = 3840.0 + 100.0; // bar 2 + a bit: SPP 17 (the next 16th), first pulse at tick 4080
+    std::int64_t sample = 0;
+    play (g, run, ticks, sample, 4, 1000, 120.0);
+    CHECK (run.sent[0].second.bytes[0] == 0xf2 && run.sent[0].second.bytes[1] == 17 && run.sent[0].second.bytes[2] == 0);
+    CHECK (run.sent[1].second.bytes[0] == 0xfb);
+    CHECK (run.sent[2].second.bytes[0] == 0xf8);
+    // 140 ticks to the pulse at 1 tick / 25 samples (120 BPM, 48 kHz: 0.04 ticks per sample)
+    CHECK (run.sent[2].first == 3500);
+    // a jump while playing (the loop goes back to 0): Stop, Start, pulse at once
+    run.sent.clear();
+    ticks = 0.0;
+    play (g, run, ticks, sample, 1, 1000, 120.0, 48000.0, true, true);
+    CHECK (run.sent.size() >= 3 && run.sent[0].second.bytes[0] == 0xfc && run.sent[1].second.bytes[0] == 0xfa && run.sent[2].second.bytes[0] == 0xf8);
+    // a big SPP: 14 bits, LSB first
+    run.sent.clear();
+    ticks = 240.0 * 1000.0;
+    play (g, run, ticks, sample, 1, 10, 120.0, 48000.0, true, true);
+    CHECK (run.sent[1].second.bytes[0] == 0xf2 && run.sent[1].second.bytes[1] == (1000 & 0x7f) && run.sent[1].second.bytes[2] == (1000 >> 7));
+}
+
+TEST (midisync165_mtc_timecode_labels_drop_frame)
+{
+    using namespace lynx::midisync;
+    const auto df = mtcRate (SyncType::mtc2997Drop);
+    CHECK (df.code == 2 && df.drop && df.nominal == 30);
+    // the first minute has every label; minute 1 starts at 00:01:00;02
+    CHECK ((frameToTimecode (1799, df) == Timecode { 0, 0, 59, 29 }));
+    CHECK ((frameToTimecode (1800, df) == Timecode { 0, 1, 0, 2 }));
+    // minute 10 keeps its 0 and 1
+    CHECK ((frameToTimecode (17982, df) == Timecode { 0, 10, 0, 0 }));
+    CHECK ((frameToTimecode (17981, df) == Timecode { 0, 9, 59, 29 }));
+    // one hour of 29.97 drop = 107 892 frames = 01:00:00;00 exactly
+    CHECK ((frameToTimecode (107892, df) == Timecode { 1, 0, 0, 0 }));
+    for (std::int64_t f : { 0, 1, 2, 1799, 1800, 1801, 3597, 3598, 17981, 17982, 17983, 107891, 107892, 500000 })
+        CHECK (timecodeToFrame (frameToTimecode (f, df), df) == f);
+    // non-drop 29.97: plain 30-frame labels (it drifts from the clock by design)
+    const auto nd = mtcRate (SyncType::mtc2997);
+    CHECK (nd.code == 3 && ! nd.drop);
+    CHECK ((frameToTimecode (1800, nd) == Timecode { 0, 1, 0, 0 }));
+    const auto f24 = mtcRate (SyncType::mtc24), f25 = mtcRate (SyncType::mtc25), f30 = mtcRate (SyncType::mtc30), d30 = mtcRate (SyncType::mtc30Drop);
+    CHECK (f24.code == 0 && f25.code == 1 && f30.code == 3 && d30.code == 2 && d30.fps == 30.0);
+    CHECK ((frameToTimecode (24 * 3661 + 5, f24) == Timecode { 1, 1, 1, 5 }));
+    CHECK ((frameToTimecode (25 * 59 + 24, f25) == Timecode { 0, 0, 59, 24 }));
+}
+
+TEST (midisync165_mtc_quarter_frames_and_full_frame)
+{
+    using namespace midisync165;
+    // the pieces of 01:23:45:12 at 25 fps
+    const Timecode tc { 1, 23, 45, 12 };
+    const std::uint8_t expect[8] { 0x0c, 0x10, 0x2d, 0x32, 0x47, 0x51, 0x61, 0x72 };
+    for (int p = 0; p < 8; ++p)
+        CHECK (quarterFrameData (tc, p, 1) == expect[p]);
+    std::uint8_t ff[10] {};
+    fullFrame (tc, 1, ff);
+    const std::uint8_t ffExpect[10] { 0xf0, 0x7f, 0x7f, 0x01, 0x01, 0x21, 23, 45, 12, 0xf7 };
+    CHECK (std::equal (ff, ff + 10, ffExpect));
+
+    for (int t = 1; t < syncTypeCount; ++t)
+    {
+        const auto type = (SyncType) t;
+        const auto rate = mtcRate (type);
+        Generator g;
+        g.setType (type);
+        Run run;
+        double ticks = 0.0;
+        std::int64_t sample = 0;
+        play (g, run, ticks, sample, 100, 480, 120.0); // 1 s
+        // a full frame at the start, then 4 quarter frames per frame, in piece order 0…7
+        CHECK (run.sent[0].second.size == 10 && run.sent[0].second.bytes[5] == (std::uint8_t) (rate.code << 5));
+        std::vector<std::pair<std::int64_t, std::uint8_t>> qf;
+        for (const auto& [at, m] : run.sent)
+            if (m.bytes[0] == 0xf1)
+                qf.push_back ({ at, m.bytes[1] });
+        const auto expected = (std::size_t) std::ceil (rate.fps * 4.0 - 1.0e-9);
+        CHECK (qf.size() == expected);
+        for (std::size_t i = 0; i < qf.size(); ++i)
+        {
+            CHECK ((qf[i].second >> 4) == (int) (i % 8));
+            CHECK (std::llabs (qf[i].first - std::llround (i * 48000.0 / (rate.fps * 4.0))) <= 1);
+        }
+        // the second sequence (frames 2–3) carries frame 2
+        CHECK ((qf[8].second & 0x0f) == 2 && (qf[9].second & 0x0f) == 0);
+        CHECK ((qf[7].second & 0x06) >> 1 == rate.code);
+    }
+
+    // a locate at 10 s (25 fps): a full frame 00:00:10:00, then quarter frames from frame 250
+    Generator g;
+    g.setType (SyncType::mtc25);
+    Run run;
+    double ticks = 10.0 * 2.0 * 960.0; // 10 s at 120 BPM
+    std::int64_t sample = 0;
+    play (g, run, ticks, sample, 10, 480, 120.0);
+    CHECK (run.sent[0].second.size == 10 && run.sent[0].second.bytes[7] == 10 && run.sent[0].second.bytes[8] == 0);
+    CHECK (run.sent[1].second.bytes[0] == 0xf1 && run.sent[1].first == 0 && run.sent[1].second.bytes[1] == (0x00 | (250 % 25)));
+    CHECK (run.sent[3].second.bytes[1] == (0x20 | 10)); // seconds low nibble
+}
+
+TEST (midisync165_receiver_tempo_from_jittery_clock)
+{
+    using namespace lynx::midisync;
+    std::mt19937 random (165);
+    std::uniform_real_distribution<double> jitter (-0.001, 0.001); // ±1 ms per message (a USB MIDI interface)
+    for (const auto bpm : { 60.0, 98.5, 120.0, 174.0, 240.0 })
+    {
+        Receiver r;
+        const std::uint8_t clock = 0xf8;
+        const auto period = 60.0 / (bpm * 24.0);
+        double shown = 0.0, maxSwing = 0.0;
+        for (int i = 0; i < 24 * 16; ++i)
+        {
+            r.feed (&clock, 1, 10.0 + i * period + jitter (random));
+            if (i >= 24 * 4)
+            {
+                if (shown > 0.0)
+                    maxSwing = std::max (maxSwing, std::abs (r.bpm() - shown));
+                shown = r.bpm();
+            }
+        }
+        CHECK (std::abs (r.bpm() - bpm) < 0.15 * bpm / 120.0 + 0.1);
+        CHECK (maxSwing < 0.3); // the hysteresis keeps the readout steady
+        CHECK (r.receiving (10.0 + 24 * 16 * period) && ! r.receiving (20.0 + 24 * 16 * period));
+    }
+    // a tempo change is followed within a beat
+    Receiver r;
+    const std::uint8_t clock = 0xf8;
+    double t = 0.0;
+    for (int i = 0; i < 96; ++i, t += 60.0 / (120.0 * 24.0))
+        r.feed (&clock, 1, t);
+    for (int i = 0; i < 24; ++i, t += 60.0 / (90.0 * 24.0))
+        r.feed (&clock, 1, t);
+    CHECK (std::abs (r.bpm() - 90.0) < 0.2);
+    // one late message does not restart the fit
+    Receiver q;
+    t = 0.0;
+    for (int i = 0; i < 96; ++i, t += 60.0 / (120.0 * 24.0))
+        q.feed (&clock, 1, t + (i == 60 ? 0.008 : 0.0));
+    CHECK (std::abs (q.bpm() - 120.0) < 0.3);
+    // a clock too fast for a tempo
+    Receiver f;
+    for (int i = 0; i < 48; ++i)
+        f.feed (&clock, 1, i * 0.0001);
+    CHECK (f.tooFast() && statusText (f, 0.0047).find ("too fast") != std::string::npos);
+    CHECK (statusText (Receiver(), 0.0) == "No clock");
+}
+
+TEST (midisync165_receiver_transport_commands_and_position)
+{
+    using namespace lynx::midisync;
+    Receiver r;
+    const std::uint8_t clock = 0xf8, start = 0xfa, stop = 0xfc, resume = 0xfb;
+    const std::uint8_t spp[3] { 0xf2, 0x10, 0x01 }; // 16 + 128 = 144 sixteenths = 36 beats
+    const auto period = 60.0 / (120.0 * 24.0);
+    Receiver::Command c;
+    double ticks = -1.0;
+    // a clock while stopped: the tempo is known, the song does not move
+    for (int i = 0; i < 30; ++i)
+        r.feed (&clock, 1, i * period);
+    CHECK (! r.running() && std::abs (r.bpm() - 120.0) < 0.05 && ! r.popCommand (c, ticks));
+    CHECK (r.feed (&start, 1, 30 * period - 0.001));
+    CHECK (r.popCommand (c, ticks) && c == Receiver::Command::start && ticks == 0.0);
+    CHECK (! r.running()); // starts on the next pulse
+    r.feed (&clock, 1, 30 * period);
+    CHECK (r.running() && r.ticksAt (30 * period) == 0.0);
+    CHECK (std::abs (r.ticksAt (30 * period + period / 2) - 20.0) < 1.0e-6);
+    CHECK (std::abs (r.ticksAt (30 * period + 3 * period) - 120.0) < 1.0e-6); // extrapolated…
+    CHECK (std::abs (r.ticksAt (30 * period + 5.0) - 40.0 * 0.1 / period) < 1.0e-6); // …at most 0.1 s
+    for (int i = 31; i < 30 + 49; ++i)
+        r.feed (&clock, 1, i * period);
+    CHECK (std::abs (r.ticksAt (78 * period) - 48 * 40.0) < 1.0e-6); // two beats in
+    r.feed (&stop, 1, 79 * period);
+    CHECK (r.popCommand (c, ticks) && c == Receiver::Command::stop && ! r.running());
+    // SPP then Continue: playback resumes at bar 10 on the next pulse
+    CHECK (r.feed (spp, 3, 80 * period));
+    CHECK (r.popCommand (c, ticks) && c == Receiver::Command::locate && ticks == 144 * 240.0);
+    r.feed (&resume, 1, 81 * period);
+    CHECK (r.popCommand (c, ticks) && c == Receiver::Command::resume && ticks == 144 * 240.0);
+    r.feed (&clock, 1, 82 * period);
+    r.feed (&clock, 1, 83 * period);
+    CHECK (r.running() && r.ticksAt (83 * period) == 144 * 240.0 + 40.0);
+    // other messages are not sync
+    const std::uint8_t note[3] { 0x90, 60, 100 };
+    CHECK (! r.feed (note, 3, 0.0));
+}
+
+TEST (midisync165_generator_feeds_receiver_loopback)
+{
+    // the self-check: what the master sends, a receiver follows (tempo, start, position)
+    using namespace midisync165;
+    Generator g;
+    Receiver r;
+    Run run;
+    double ticks = 0.0;
+    std::int64_t sample = 0;
+    play (g, run, ticks, sample, 200, 256, 133.0, 44100.0);
+    for (const auto& [at, m] : run.sent)
+        r.feed (m.bytes.data(), m.size, at / 44100.0);
+    CHECK (std::abs (r.bpm() - 133.0) < 0.05);
+    CHECK (r.running());
+    const auto now = sample / 44100.0;
+    CHECK (std::abs (r.ticksAt (now) - ticks) <= 40.0);
+    Receiver::Command c;
+    double at = 0.0;
+    CHECK (r.popCommand (c, at) && c == Receiver::Command::start);
+}
+
+TEST (midisync165_settings_round_trip)
+{
+    lynx::prefs::MidiPrefs p;
+    lynx::prefs::MidiOutputPrefs o;
+    o.name = "Volca | Sample";
+    o.masterSync = true;
+    o.syncType = "mtc2997drop";
+    o.offsetMs = -12;
+    o.allNotesOff = true;
+    p.setOutput (o);
+    p.clockInput = "TR-8S";
+    p.clockOffsetMs = 7;
+    const auto back = lynx::prefs::MidiPrefs::fromText (p.toText());
+    CHECK (back == p);
+    CHECK (back.output ("Volca | Sample").syncType == "mtc2997drop");
+    CHECK (! back.output ("other").masterSync && back.output ("other").syncType == "clock");
+    // defaults are not stored
+    lynx::prefs::MidiOutputPrefs plain;
+    plain.name = "x";
+    p.setOutput (plain);
+    CHECK (p.outputs.size() == 1);
+    CHECK (lynx::midisync::syncTypeFromKey ("bogus") == lynx::midisync::SyncType::midiClock);
+    for (int t = 0; t < lynx::midisync::syncTypeCount; ++t)
+        CHECK (lynx::midisync::syncTypeFromKey (lynx::midisync::syncTypeKey ((lynx::midisync::SyncType) t)) == (lynx::midisync::SyncType) t);
+}

+ 3 - 1
tests/tests.cpp

@@ -55,7 +55,8 @@
 #include "core/MissingFiles.h"
 #include "core/PianoRollTools.h"
 #include "core/EventEdit.h"
-#include "core/Preferences.h"
+include "core/Preferences.h"
+#include "core/MidiSync.h"
 #include "core/History.h"
 #include "core/Gms.h"
 #include "core/PoiZone.h"
@@ -16041,6 +16042,7 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "Workflow163cTests.inc"
 #include "ClipPitch164Tests.inc"
 #include "Misc164mTests.inc"
+#include "MidiSync165Tests.inc"
 #include "Theme162Tests.inc"
 #include "PluginPresets162Tests.inc"
 #include "Look162Tests.inc"