MidiSyncIo.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. #include "engine/MidiSyncIo.h"
  2. #include <algorithm>
  3. #include <chrono>
  4. #include <cmath>
  5. #include <deque>
  6. #include <mutex>
  7. #include <random>
  8. #include <thread>
  9. #if JUCE_WINDOWS
  10. extern "C" __declspec (dllimport) unsigned int __stdcall timeBeginPeriod (unsigned int);
  11. extern "C" __declspec (dllimport) unsigned int __stdcall timeEndPeriod (unsigned int);
  12. #endif
  13. namespace lynx
  14. {
  15. namespace
  16. {
  17. void atomicMax (std::atomic<double>& a, double v) noexcept
  18. {
  19. auto now = a.load (std::memory_order_relaxed);
  20. while (v > now && ! a.compare_exchange_weak (now, v, std::memory_order_relaxed))
  21. {
  22. }
  23. }
  24. void atomicAdd (std::atomic<double>& a, double v) noexcept
  25. {
  26. auto now = a.load (std::memory_order_relaxed);
  27. while (! a.compare_exchange_weak (now, now + v, std::memory_order_relaxed))
  28. {
  29. }
  30. }
  31. } // namespace
  32. MidiSyncIo::MidiSyncIo() : juce::Thread ("LYNX MIDI sync") {}
  33. MidiSyncIo::~MidiSyncIo()
  34. {
  35. stopThread (2000);
  36. const juce::ScopedLock lock (outputLock);
  37. for (auto& s : slots)
  38. s.device.reset();
  39. }
  40. void MidiSyncIo::configure (const prefs::MidiPrefs& prefs, bool devices, bool dryRun)
  41. {
  42. dry.store (dryRun);
  43. {
  44. const juce::SpinLock::ScopedLockType lock (clockNameLock);
  45. clockName = juce::String::fromUTF8 (prefs.clockInput.c_str());
  46. }
  47. clockOffsetMs.store (juce::jlimit (-1000, 1000, prefs.clockOffsetMs));
  48. if (following.exchange (! prefs.clockInput.empty()) != ! prefs.clockInput.empty())
  49. clockIn.reset();
  50. // the outputs that need a device: sync or notes off on
  51. std::vector<prefs::MidiOutputPrefs> wanted;
  52. for (const auto& o : prefs.outputs)
  53. if (o.masterSync || o.allNotesOff)
  54. wanted.push_back (o);
  55. if ((int) wanted.size() > maxOutputs)
  56. wanted.resize (maxOutputs);
  57. const auto available = devices ? juce::MidiOutput::getAvailableDevices() : juce::Array<juce::MidiDeviceInfo>();
  58. auto any = false;
  59. for (int i = 0; i < maxOutputs; ++i)
  60. {
  61. auto& slot = slots[(std::size_t) i];
  62. const prefs::MidiOutputPrefs* want = i < (int) wanted.size() ? &wanted[(std::size_t) i] : nullptr;
  63. const auto sameDevice = want != nullptr && slot.name == want->name && (slot.device != nullptr || ! devices);
  64. if (! sameDevice)
  65. {
  66. slot.active.store (false);
  67. std::unique_ptr<juce::MidiOutput> opened;
  68. if (want != nullptr && devices)
  69. for (const auto& d : available)
  70. if (d.name.toStdString() == want->name)
  71. {
  72. opened = juce::MidiOutput::openDevice (d.identifier);
  73. break;
  74. }
  75. {
  76. const juce::ScopedLock lock (outputLock);
  77. slot.device = std::move (opened);
  78. }
  79. slot.name = want != nullptr ? want->name : std::string();
  80. }
  81. slot.sync = want != nullptr && want->masterSync;
  82. slot.notesOff = want != nullptr && want->allNotesOff;
  83. const auto type = (int) midisync::syncTypeFromKey (want != nullptr ? want->syncType : std::string());
  84. if (slot.type.exchange (type) != type || ! sameDevice)
  85. slot.generation.fetch_add (1);
  86. slot.offsetMs.store (want != nullptr ? juce::jlimit (-1000, 1000, want->offsetMs) : 0);
  87. slot.active.store (slot.sync && (slot.device != nullptr || ! devices));
  88. any = any || slot.active.load();
  89. }
  90. anySync.store (any);
  91. if ((devices || dryRun) && any && ! isThreadRunning())
  92. startThread (juce::Thread::Priority::highest);
  93. }
  94. void MidiSyncIo::sendAllNotesOff()
  95. {
  96. const juce::ScopedLock lock (outputLock);
  97. for (auto& s : slots)
  98. if (s.notesOff && s.device != nullptr)
  99. for (int ch = 1; ch <= 16; ++ch)
  100. {
  101. s.device->sendMessageNow (juce::MidiMessage::controllerEvent (ch, 64, 0));
  102. s.device->sendMessageNow (juce::MidiMessage::allNotesOff (ch));
  103. }
  104. }
  105. void MidiSyncIo::deviceStarted (double rate, int bufferSize, int outputLatencySamples) noexcept
  106. {
  107. sampleRate = rate > 0.0 ? rate : 44100.0;
  108. // the audio of a block computed now is heard one buffer plus the device's latency later: the sync messages for
  109. // its samples are due then
  110. latencyMs = 1000.0 * (bufferSize + std::max (0, outputLatencySamples)) / sampleRate;
  111. predictedMs = -1.0;
  112. for (auto& s : slots)
  113. s.generator.reset();
  114. }
  115. void MidiSyncIo::beginBlock (Transport& transport, double callbackMs, int numSamples) noexcept
  116. {
  117. // the block clock: callbacks wake up with jitter, the samples don't. Follow the sample count and pull towards
  118. // the callback times slowly; resynchronise after a gap (xrun, device restart).
  119. if (predictedMs < 0.0 || std::abs (callbackMs - predictedMs) > 50.0)
  120. blockStartMs = callbackMs;
  121. else
  122. blockStartMs = predictedMs + 0.02 * (callbackMs - predictedMs);
  123. predictedMs = blockStartMs + 1000.0 * numSamples / sampleRate;
  124. if (! following.load (std::memory_order_relaxed))
  125. {
  126. if (wasFollowing)
  127. transport.externalBpm.store (0.0, std::memory_order_relaxed);
  128. wasFollowing = false;
  129. waitingFirstPulse = false;
  130. appliedBpm.store (0.0, std::memory_order_relaxed);
  131. return;
  132. }
  133. wasFollowing = true;
  134. midisync::Receiver::Command command;
  135. double ticks = 0.0;
  136. while (clockIn.popCommand (command, ticks))
  137. switch (command)
  138. {
  139. case midisync::Receiver::Command::start:
  140. case midisync::Receiver::Command::resume:
  141. transport.playing.store (false, std::memory_order_relaxed);
  142. transport.positionTicks.store (ticks, std::memory_order_relaxed);
  143. waitingFirstPulse = true;
  144. break;
  145. case midisync::Receiver::Command::stop:
  146. transport.playing.store (false, std::memory_order_relaxed);
  147. waitingFirstPulse = false;
  148. break;
  149. case midisync::Receiver::Command::locate:
  150. if (! transport.playing.load (std::memory_order_relaxed))
  151. transport.positionTicks.store (ticks, std::memory_order_relaxed);
  152. break;
  153. case midisync::Receiver::Command::none: break;
  154. }
  155. if (waitingFirstPulse && clockIn.running())
  156. {
  157. waitingFirstPulse = false;
  158. transport.playing.store (true, std::memory_order_relaxed);
  159. }
  160. const auto nowSeconds = blockStartMs * 0.001;
  161. const auto bpm = clockIn.receiving (nowSeconds) ? clockIn.bpm() : 0.0;
  162. auto applied = bpm;
  163. if (bpm > 0.0 && clockIn.running() && transport.playing.load (std::memory_order_relaxed))
  164. {
  165. // phase lock: the block's first sample is heard `latencyMs` from now; it should then be where the master is
  166. // (plus the user's offset: positive = LYNX later)
  167. const auto target = clockIn.ticksAt (nowSeconds + (latencyMs - clockOffsetMs.load (std::memory_order_relaxed)) * 0.001);
  168. const auto position = transport.positionTicks.load (std::memory_order_relaxed);
  169. const auto error = target - position;
  170. if (std::abs (error) > 480.0) // half a beat off (a jump on the master's side): relocate
  171. transport.positionTicks.store (target, std::memory_order_relaxed);
  172. else // pull in within ~0.5 s, at most ±5 % of the tempo
  173. applied = bpm * std::clamp (1.0 + error / (bpm * 16.0 * 0.5), 0.95, 1.05);
  174. }
  175. transport.externalBpm.store (applied, std::memory_order_relaxed);
  176. appliedBpm.store (bpm, std::memory_order_relaxed);
  177. }
  178. void MidiSyncIo::subBlock (double startTicks, double ticksPerSample, int numSamples, int offset, bool playing) noexcept
  179. {
  180. if (! anySync.load (std::memory_order_relaxed))
  181. return;
  182. const auto t0 = juce::Time::getHighResolutionTicks();
  183. for (auto& slot : slots)
  184. {
  185. if (! slot.active.load (std::memory_order_relaxed))
  186. continue;
  187. if (const auto g = slot.generation.load (std::memory_order_acquire); g != slot.seenGeneration)
  188. {
  189. slot.seenGeneration = g;
  190. slot.generator.reset();
  191. slot.generator.setType ((midisync::SyncType) slot.type.load (std::memory_order_relaxed));
  192. }
  193. midisync::Block block;
  194. block.startTicks = startTicks;
  195. block.ticksPerSample = ticksPerSample;
  196. block.sampleRate = sampleRate;
  197. block.numSamples = numSamples;
  198. block.playing = playing;
  199. scratch.clear();
  200. const auto songSeconds = ticksPerSample > 0.0 ? startTicks / (ticksPerSample * sampleRate) : 0.0;
  201. slot.generator.process (block, songSeconds, scratch);
  202. const auto base = blockStartMs + latencyMs + slot.offsetMs.load (std::memory_order_relaxed);
  203. for (int i = 0; i < scratch.count; ++i)
  204. {
  205. const auto& m = scratch.items[(std::size_t) i];
  206. if (! slot.queue.push ({ base + 1000.0 * (offset + m.sample) / sampleRate, m }))
  207. droppedCount.fetch_add (1, std::memory_order_relaxed);
  208. }
  209. }
  210. const auto us = 1.0e6 * juce::Time::highResolutionTicksToSeconds (juce::Time::getHighResolutionTicks() - t0);
  211. atomicAdd (blockSum, us);
  212. atomicMax (blockMax, us);
  213. blockN.fetch_add (1, std::memory_order_relaxed);
  214. }
  215. void MidiSyncIo::run()
  216. {
  217. #if JUCE_WINDOWS
  218. timeBeginPeriod (1); // 1 ms sleeps for this thread's waits
  219. #endif
  220. std::array<std::deque<Timed>, maxOutputs> pending;
  221. while (! threadShouldExit())
  222. {
  223. auto any = false;
  224. for (int i = 0; i < maxOutputs; ++i)
  225. {
  226. Timed t;
  227. while (slots[(std::size_t) i].queue.pop (t))
  228. pending[(std::size_t) i].push_back (t);
  229. any = any || ! pending[(std::size_t) i].empty();
  230. }
  231. if (! any)
  232. {
  233. if (! anySync.load())
  234. wait (50);
  235. else
  236. std::this_thread::sleep_for (std::chrono::microseconds (500));
  237. continue;
  238. }
  239. auto now = juce::Time::getMillisecondCounterHiRes();
  240. auto next = now + 1000.0;
  241. {
  242. const juce::ScopedLock lock (outputLock);
  243. for (int i = 0; i < maxOutputs; ++i)
  244. {
  245. auto& queue = pending[(std::size_t) i];
  246. auto* device = slots[(std::size_t) i].device.get();
  247. while (! queue.empty() && queue.front().dueMs <= now + 0.05)
  248. {
  249. const auto& m = queue.front().message;
  250. if (device != nullptr || dry.load (std::memory_order_relaxed))
  251. {
  252. if (device != nullptr)
  253. device->sendMessageNow (juce::MidiMessage (m.bytes.data(), (int) m.size));
  254. now = juce::Time::getMillisecondCounterHiRes();
  255. const auto late = std::max (0.0, now - queue.front().dueMs);
  256. atomicAdd (lateSum, late);
  257. atomicMax (lateMax, late);
  258. lateN.fetch_add (1, std::memory_order_relaxed);
  259. sentCount.fetch_add (1, std::memory_order_relaxed);
  260. }
  261. queue.pop_front();
  262. }
  263. if (! queue.empty())
  264. next = std::min (next, queue.front().dueMs);
  265. }
  266. }
  267. // sleep until shortly before the next message, then in short steps
  268. const auto wait = next - juce::Time::getMillisecondCounterHiRes();
  269. if (wait > 2.0)
  270. std::this_thread::sleep_for (std::chrono::microseconds ((int) ((wait - 1.0) * 1000.0)));
  271. else if (wait > 0.05)
  272. std::this_thread::sleep_for (std::chrono::microseconds (100));
  273. }
  274. #if JUCE_WINDOWS
  275. timeEndPeriod (1);
  276. #endif
  277. }
  278. bool MidiSyncIo::handleInput (const juce::String& device, const juce::MidiMessage& m) noexcept
  279. {
  280. if (! following.load (std::memory_order_relaxed))
  281. return false;
  282. {
  283. const juce::SpinLock::ScopedLockType lock (clockNameLock);
  284. if (device != clockName)
  285. return false;
  286. }
  287. // (JUCE time-stamps input in seconds on Time::getMillisecondCounterHiRes()'s clock)
  288. return clockIn.feed (m.getRawData(), m.getRawDataSize(), m.getTimeStamp());
  289. }
  290. std::string MidiSyncIo::clockStatus() const
  291. {
  292. return midisync::statusText (clockIn, juce::Time::getMillisecondCounterHiRes() * 0.001);
  293. }
  294. double MidiSyncIo::followedBpm() const noexcept
  295. {
  296. return appliedBpm.load (std::memory_order_relaxed);
  297. }
  298. MidiSyncIo::Stats MidiSyncIo::stats() const
  299. {
  300. // the last second's numbers (read and reset at most once a second)
  301. const auto now = juce::Time::getMillisecondCounterHiRes();
  302. if (now - lastStatsMs < 1000.0)
  303. return lastStats;
  304. lastStatsMs = now;
  305. auto& self = const_cast<MidiSyncIo&> (*this);
  306. Stats s;
  307. s.sent = sentCount.load();
  308. s.dropped = droppedCount.load();
  309. const auto ln = self.lateN.exchange (0);
  310. s.meanLateMs = ln > 0 ? self.lateSum.exchange (0.0) / (double) ln : 0.0;
  311. s.maxLateMs = self.lateMax.exchange (0.0);
  312. const auto bn = self.blockN.exchange (0);
  313. s.meanBlockUs = bn > 0 ? self.blockSum.exchange (0.0) / (double) bn : 0.0;
  314. s.maxBlockUs = self.blockMax.exchange (0.0);
  315. lastStats = s;
  316. return s;
  317. }
  318. juce::String MidiSyncIo::selfTest (const juce::String& outputName, const juce::String& inputName)
  319. {
  320. juce::String report;
  321. // 1. in memory: the generator's clock (time-stamped with ±0.5 ms of jitter) followed by a receiver
  322. {
  323. std::mt19937 random (165);
  324. std::uniform_real_distribution<double> jitter (-0.0005, 0.0005);
  325. for (const auto bpm : { 90.0, 120.0, 174.0 })
  326. {
  327. midisync::Generator g;
  328. midisync::Receiver r;
  329. const double rate = 48000.0, tps = bpm * 960.0 / (60.0 * rate);
  330. double ticks = 0.0;
  331. std::int64_t sample = 0;
  332. midisync::BlockMessages out;
  333. for (int b = 0; b < 48000 * 8 / 256; ++b)
  334. {
  335. midisync::Block block;
  336. block.startTicks = ticks;
  337. block.ticksPerSample = tps;
  338. block.sampleRate = rate;
  339. block.numSamples = 256;
  340. block.playing = true;
  341. out.clear();
  342. g.process (block, 0.0, out);
  343. for (int i = 0; i < out.count; ++i)
  344. r.feed (out.items[(std::size_t) i].bytes.data(), out.items[(std::size_t) i].size,
  345. (double) (sample + out.items[(std::size_t) i].sample) / rate + jitter (random));
  346. ticks += 256 * tps;
  347. sample += 256;
  348. }
  349. const auto positionError = r.ticksAt ((double) sample / rate) - ticks;
  350. report << "loopback bpm=" << bpm << " received=" << juce::String (r.bpm(), 3) << " error=" << juce::String (r.bpm() - bpm, 3)
  351. << " position error ticks=" << juce::String (positionError, 2) << " running=" << (r.running() ? 1 : 0) << "\n";
  352. }
  353. }
  354. // 2. the sender thread at real time
  355. MidiSyncIo io;
  356. prefs::MidiPrefs p;
  357. prefs::MidiOutputPrefs o;
  358. o.name = outputName.isNotEmpty() ? outputName.toStdString() : std::string ("(dry run)");
  359. o.masterSync = true;
  360. p.setOutput (o);
  361. const auto real = outputName.isNotEmpty();
  362. io.configure (p, real, ! real);
  363. report << "output=" << (real ? outputName : juce::String ("(dry run, timed without a device)")) << " opened=" << (io.sending() ? 1 : 0) << "\n";
  364. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  365. report << " midi-out=" << d.name << "\n";
  366. for (const auto& d : juce::MidiInput::getAvailableDevices())
  367. report << " midi-in=" << d.name << "\n";
  368. // the input side of a loopback: a receiver fed from the input callback
  369. struct In final : juce::MidiInputCallback
  370. {
  371. midisync::Receiver receiver;
  372. std::vector<double> times;
  373. std::mutex lock;
  374. void handleIncomingMidiMessage (juce::MidiInput*, const juce::MidiMessage& m) override
  375. {
  376. receiver.feed (m.getRawData(), m.getRawDataSize(), m.getTimeStamp());
  377. if (m.getRawDataSize() > 0 && m.getRawData()[0] == 0xf8)
  378. {
  379. const std::lock_guard<std::mutex> g (lock);
  380. times.push_back (juce::Time::getMillisecondCounterHiRes());
  381. }
  382. }
  383. } in;
  384. std::unique_ptr<juce::MidiInput> input;
  385. if (inputName.isNotEmpty())
  386. for (const auto& d : juce::MidiInput::getAvailableDevices())
  387. if (d.name == inputName)
  388. input = juce::MidiInput::openDevice (d.identifier, &in);
  389. if (input != nullptr)
  390. input->start();
  391. if (io.sending())
  392. {
  393. Transport transport;
  394. transport.sampleRate.store (48000.0);
  395. transport.bpm.store (120.0);
  396. transport.playing.store (true);
  397. io.deviceStarted (48000.0, 256, 0);
  398. const auto start = juce::Time::getMillisecondCounterHiRes();
  399. for (int b = 0; b < 48000 * 5 / 256; ++b)
  400. {
  401. // wake up like an audio callback (with the scheduler's jitter), on the block's due time
  402. const auto due = start + b * 256.0 * 1000.0 / 48000.0;
  403. while (juce::Time::getMillisecondCounterHiRes() < due)
  404. std::this_thread::sleep_for (std::chrono::microseconds (200));
  405. io.beginBlock (transport, juce::Time::getMillisecondCounterHiRes(), 256);
  406. const auto tps = transport.ticksPerSample();
  407. io.subBlock (transport.positionTicks.load(), tps, 256, 0, true);
  408. transport.positionTicks.store (transport.positionTicks.load() + 256 * tps);
  409. }
  410. std::this_thread::sleep_for (std::chrono::milliseconds (100));
  411. io.lastStatsMs = 0.0;
  412. const auto s = io.stats();
  413. report << "sender: sent=" << (juce::int64) s.sent << " dropped=" << (juce::int64) s.dropped << " late mean ms=" << juce::String (s.meanLateMs, 3)
  414. << " max ms=" << juce::String (s.maxLateMs, 3) << " (5 s)\n";
  415. report << "audio thread per block: mean us=" << juce::String (s.meanBlockUs, 2) << " max us=" << juce::String (s.maxBlockUs, 2) << "\n";
  416. }
  417. if (input != nullptr)
  418. {
  419. input->stop();
  420. const std::lock_guard<std::mutex> g (in.lock);
  421. double sum = 0.0, sum2 = 0.0;
  422. const auto n = (int) in.times.size() - 1;
  423. for (int i = 0; i < n; ++i)
  424. {
  425. const auto d = in.times[(std::size_t) i + 1] - in.times[(std::size_t) i];
  426. sum += d;
  427. sum2 += d * d;
  428. }
  429. const auto mean = n > 0 ? sum / n : 0.0;
  430. report << "input=" << inputName << " clocks=" << (int) in.times.size() << " interval mean ms=" << juce::String (mean, 3)
  431. << " sd ms=" << juce::String (n > 0 ? std::sqrt (std::max (0.0, sum2 / n - mean * mean)) : 0.0, 3)
  432. << " received bpm=" << juce::String (in.receiver.bpm(), 2) << "\n";
  433. }
  434. else if (inputName.isNotEmpty())
  435. report << "input=" << inputName << " not found\n";
  436. return report;
  437. }
  438. } // namespace lynx