Channels.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. /* Copyright 2025, Ableton AG, Berlin. All rights reserved.
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. * If you would like to incorporate Link into a proprietary software application,
  17. * please contact <link-devs@ableton.com>.
  18. */
  19. #pragma once
  20. #include <ableton/discovery/AsioTypes.hpp>
  21. #include <ableton/link_audio/ChannelAnnouncements.hpp>
  22. #include <ableton/link_audio/Id.hpp>
  23. #include <ableton/link_audio/PeerAnnouncement.hpp>
  24. #include <ableton/util/Injected.hpp>
  25. #include <algorithm>
  26. #include <cassert>
  27. #include <chrono>
  28. #include <map>
  29. #include <memory>
  30. #include <optional>
  31. #include <stdexcept>
  32. #include <string>
  33. #include <tuple>
  34. #include <vector>
  35. namespace ableton
  36. {
  37. namespace link_audio
  38. {
  39. template <typename IoContext, typename Callback, typename Interface>
  40. class Channels
  41. {
  42. // non-movable private implementation type
  43. struct Impl;
  44. public:
  45. struct SendHandler
  46. {
  47. SendHandler(discovery::UdpEndpoint endpoint, std::shared_ptr<Interface> interface)
  48. : mEndpoint(endpoint)
  49. , mpInterface(interface)
  50. {
  51. }
  52. std::size_t operator()(const uint8_t* const pData, const size_t numBytes)
  53. {
  54. if (auto interface = mpInterface.lock())
  55. {
  56. try
  57. {
  58. return interface->send(pData, numBytes, mEndpoint);
  59. }
  60. catch (const std::runtime_error&)
  61. {
  62. }
  63. }
  64. return 0;
  65. }
  66. discovery::UdpEndpoint endpoint() const { return mEndpoint; }
  67. private:
  68. discovery::UdpEndpoint mEndpoint;
  69. std::weak_ptr<Interface> mpInterface;
  70. };
  71. struct Channel
  72. {
  73. std::string name;
  74. Id id;
  75. std::string peerName;
  76. Id peerId;
  77. Id sessionId;
  78. friend bool operator==(const Channel& lhs, const Channel& rhs)
  79. {
  80. return std::tie(lhs.name, lhs.id, lhs.peerName, lhs.peerId, lhs.sessionId)
  81. == std::tie(rhs.name, rhs.id, rhs.peerName, rhs.peerId, rhs.sessionId);
  82. }
  83. };
  84. struct ChannelInfo
  85. {
  86. Channel channel;
  87. discovery::IpAddress gatewayAddr;
  88. };
  89. struct ChannelInfoCompare
  90. {
  91. bool operator()(const ChannelInfo& lhs, const ChannelInfo& rhs) const
  92. {
  93. if (lhs.channel.sessionId == rhs.channel.sessionId)
  94. {
  95. if (lhs.channel.peerId == rhs.channel.peerId)
  96. {
  97. if (lhs.channel.id == rhs.channel.id)
  98. {
  99. return lhs.gatewayAddr < rhs.gatewayAddr;
  100. }
  101. return lhs.channel.channelId < rhs.channel.channelId;
  102. }
  103. return lhs.channel.peerId < rhs.channel.peerId;
  104. }
  105. return lhs.channel.sessionId < rhs.channel.sessionId;
  106. }
  107. };
  108. Channels(util::Injected<IoContext> io, Callback callback)
  109. : mpImpl(std::make_shared<Impl>(std::move(io), std::move(callback)))
  110. {
  111. }
  112. std::vector<Channel> sessionChannels(const link::SessionId& sessionId) const
  113. {
  114. using namespace std;
  115. vector<Channel> result;
  116. auto& channelsVec = mpImpl->mChannels;
  117. for (const auto& channel : mpImpl->mChannels)
  118. {
  119. if (channel.channel.sessionId == sessionId)
  120. {
  121. result.push_back(channel.channel);
  122. }
  123. }
  124. return result;
  125. }
  126. std::vector<Channel> uniqueSessionChannels(const link::SessionId& sessionId) const
  127. {
  128. auto channels = sessionChannels(sessionId);
  129. auto it = std::unique(begin(channels),
  130. end(channels),
  131. [](const auto& a, const auto& b) { return a.id == b.id; });
  132. return {begin(channels), it};
  133. }
  134. std::optional<SendHandler> peerSendHandler(const Id peerId) const
  135. {
  136. auto it = mpImpl->mPeerSendHandlers.find(peerId);
  137. return it != mpImpl->mPeerSendHandlers.end() ? std::optional{it->second.handler}
  138. : std::nullopt;
  139. }
  140. std::optional<SendHandler> channelSendHandler(const Id channelId) const
  141. {
  142. const auto& channels = mpImpl->mChannels;
  143. const auto it =
  144. std::find_if(begin(channels),
  145. end(channels),
  146. [&](const auto& info) { return info.channel.id == channelId; });
  147. return it != end(channels) ? peerSendHandler(it->channel.peerId) : std::nullopt;
  148. }
  149. template <typename PeerIdIt>
  150. void prunePeerChannels(PeerIdIt connectedPeersBegin, PeerIdIt connectedPeersEnd)
  151. {
  152. mpImpl->prunePeerChannels(connectedPeersBegin, connectedPeersEnd);
  153. }
  154. struct GatewayObserver
  155. {
  156. using GatewayObserverAnnouncement = PeerAnnouncement;
  157. using GatewayObserverNodeId = link::NodeId;
  158. GatewayObserver(std::shared_ptr<Impl> pImpl, discovery::IpAddress addr)
  159. : mpImpl(std::move(pImpl))
  160. , mAddr(std::move(addr))
  161. {
  162. }
  163. GatewayObserver(const GatewayObserver&) = delete;
  164. GatewayObserver(GatewayObserver&& rhs)
  165. : mpImpl(std::move(rhs.mpImpl))
  166. , mAddr(std::move(rhs.mAddr))
  167. {
  168. }
  169. ~GatewayObserver()
  170. {
  171. // Check to handle the moved from case
  172. if (mpImpl)
  173. {
  174. mpImpl->gatewayClosed(mAddr);
  175. }
  176. }
  177. // model the observer concept from Channels
  178. template <typename Announcement>
  179. friend void sawAnnouncement(GatewayObserver& observer, Announcement announcement)
  180. {
  181. auto pImpl = observer.mpImpl;
  182. auto addr = observer.mAddr;
  183. assert(pImpl);
  184. pImpl->sawAnnouncementOnGateway(std::move(announcement), std::move(addr));
  185. }
  186. template <typename It>
  187. friend void channelsLeft(GatewayObserver& observer, It channelsBegin, It channelsEnd)
  188. {
  189. auto pImpl = observer.mpImpl;
  190. auto addr = observer.mAddr;
  191. pImpl->channelsLeftGateway(std::move(addr), channelsBegin, channelsEnd);
  192. }
  193. std::shared_ptr<Impl> mpImpl;
  194. discovery::IpAddress mAddr;
  195. };
  196. // Factory function for the gateway observer
  197. friend GatewayObserver makeGatewayObserver(Channels& channels,
  198. discovery::IpAddress addr)
  199. {
  200. return GatewayObserver{channels.mpImpl, std::move(addr)};
  201. }
  202. private:
  203. using Timer = typename util::Injected<IoContext>::type::Timer;
  204. using TimerError = typename Timer::ErrorCode;
  205. using TimePoint = typename Timer::TimePoint;
  206. struct TimeoutCompare
  207. {
  208. bool operator()(const std::tuple<TimePoint, discovery::IpAddress, Id>& lhs,
  209. const std::tuple<TimePoint, discovery::IpAddress, Id>& rhs) const
  210. {
  211. return std::get<TimePoint>(lhs) < std::get<TimePoint>(rhs);
  212. }
  213. };
  214. struct Impl
  215. {
  216. Impl(util::Injected<IoContext> io, Callback callback)
  217. : mIo(std::move(io))
  218. , mCallback(std::move(callback))
  219. , mPruneTimer(mIo->makeTimer())
  220. {
  221. }
  222. template <typename Announcement>
  223. void sawAnnouncementOnGateway(Announcement incoming, discovery::IpAddress gatewayAddr)
  224. {
  225. using namespace std;
  226. const auto peerSession = incoming.announcement.sessionId;
  227. const auto nodeId = incoming.announcement.nodeId;
  228. const auto peerInfo = incoming.announcement.peerInfo;
  229. const auto peerAudioChannels = incoming.announcement.channels.channels;
  230. const auto ttl = incoming.ttl;
  231. auto sendHandler = SendHandler(incoming.from, incoming.pInterface);
  232. const auto networkQuality = incoming.networkQuality;
  233. bool didChannelsChange = false;
  234. for (const auto& peerChannel : peerAudioChannels)
  235. {
  236. const auto channelInfo = ChannelInfo{
  237. {peerChannel.name, peerChannel.id, peerInfo.name, nodeId, peerSession},
  238. gatewayAddr};
  239. {
  240. const auto timeout =
  241. std::find_if(begin(mChannelTimeouts),
  242. end(mChannelTimeouts),
  243. [&](const auto& timeout)
  244. {
  245. return std::get<discovery::IpAddress>(timeout) == gatewayAddr
  246. && std::get<Id>(timeout) == channelInfo.channel.id;
  247. });
  248. if (timeout != end(mChannelTimeouts))
  249. {
  250. mChannelTimeouts.erase(timeout);
  251. }
  252. auto newTo = std::make_tuple(mPruneTimer.now() + std::chrono::seconds(ttl),
  253. gatewayAddr,
  254. channelInfo.channel.id);
  255. mChannelTimeouts.insert(
  256. upper_bound(
  257. begin(mChannelTimeouts), end(mChannelTimeouts), newTo, TimeoutCompare{}),
  258. newTo);
  259. }
  260. const auto idRange = equal_range(begin(mChannels),
  261. end(mChannels),
  262. channelInfo,
  263. [](const auto& a, const auto& b)
  264. { return a.channel.id < b.channel.id; });
  265. if (idRange.first == idRange.second)
  266. {
  267. // This channel is not currently known on any gateway
  268. didChannelsChange = true;
  269. mChannels.insert(idRange.first, std::move(channelInfo));
  270. }
  271. else
  272. {
  273. // was it on this gateway?
  274. const auto addrRange = equal_range(idRange.first,
  275. idRange.second,
  276. channelInfo,
  277. [](const auto& a, const auto& b)
  278. { return a.gatewayAddr < b.gatewayAddr; });
  279. if (addrRange.first == addrRange.second)
  280. {
  281. // First time on this gateway, add it
  282. mChannels.insert(addrRange.first, std::move(channelInfo));
  283. }
  284. else
  285. {
  286. // We have an entry for this channel on this gateway, update it
  287. // callback if the name of the first entry changed
  288. auto cmp = [](const auto& lhs, const auto& rhs)
  289. {
  290. return std::tie(lhs.name, lhs.sessionId, lhs.peerName, lhs.peerId)
  291. == std::tie(rhs.name, rhs.sessionId, rhs.peerName, rhs.peerId);
  292. };
  293. const auto firstChannelChanged =
  294. addrRange.first == idRange.first
  295. && !cmp(addrRange.first->channel, channelInfo.channel);
  296. didChannelsChange = didChannelsChange || firstChannelChanged;
  297. *addrRange.first = std::move(channelInfo);
  298. }
  299. }
  300. }
  301. if (mPeerSendHandlers.count(nodeId) == 0)
  302. {
  303. mPeerSendHandlers.emplace(nodeId, PeerSendHandler{sendHandler, networkQuality});
  304. }
  305. else if (mPeerSendHandlers.at(nodeId).networkQuality < networkQuality)
  306. {
  307. mPeerSendHandlers.insert_or_assign(
  308. nodeId, PeerSendHandler{sendHandler, networkQuality});
  309. }
  310. // Invoke callbacks outside the critical section
  311. if (didChannelsChange)
  312. {
  313. mCallback();
  314. }
  315. scheduleNextPruning();
  316. }
  317. template <typename PeerIdIt>
  318. void prunePeerSendHandlers(PeerIdIt connectedPeersBegin, PeerIdIt connectedPeersEnd)
  319. {
  320. using namespace std;
  321. for (auto it = begin(mPeerSendHandlers); it != end(mPeerSendHandlers);)
  322. {
  323. if (none_of(connectedPeersBegin,
  324. connectedPeersEnd,
  325. [&](const auto& peerId) { return peerId == it->first; }))
  326. {
  327. it = mPeerSendHandlers.erase(it);
  328. }
  329. else
  330. {
  331. ++it;
  332. }
  333. }
  334. }
  335. void pruneSendHandlers()
  336. {
  337. using namespace std;
  338. auto peerIds = vector<Id>{};
  339. peerIds.reserve(mChannels.size());
  340. transform(begin(mChannels),
  341. end(mChannels),
  342. back_inserter(peerIds),
  343. [](const auto& info) { return info.channel.peerId; });
  344. prunePeerSendHandlers(begin(peerIds), end(peerIds));
  345. }
  346. template <typename PeerIdIt>
  347. void prunePeerChannels(PeerIdIt connectedPeersBegin, PeerIdIt connectedPeersEnd)
  348. {
  349. using namespace std;
  350. vector<Id> removedChannelIds;
  351. for (const auto& info : mChannels)
  352. {
  353. if (none_of(connectedPeersBegin,
  354. connectedPeersEnd,
  355. [&](const auto& peerId) { return peerId == info.channel.peerId; }))
  356. {
  357. removedChannelIds.push_back(info.channel.id);
  358. }
  359. }
  360. auto it = remove_if(begin(mChannels),
  361. end(mChannels),
  362. [&](auto& info)
  363. {
  364. return none_of(connectedPeersBegin,
  365. connectedPeersEnd,
  366. [&](const auto& peerId)
  367. { return peerId == info.channel.peerId; });
  368. });
  369. const auto channelsChanged = it != end(mChannels);
  370. mChannels.erase(it, end(mChannels));
  371. mChannelTimeouts.erase(
  372. remove_if(begin(mChannelTimeouts),
  373. end(mChannelTimeouts),
  374. [&](const auto& timeout)
  375. {
  376. const auto& id = std::get<Id>(timeout);
  377. return find(begin(removedChannelIds), end(removedChannelIds), id)
  378. != end(removedChannelIds);
  379. }),
  380. end(mChannelTimeouts));
  381. scheduleNextPruning();
  382. prunePeerSendHandlers(connectedPeersBegin, connectedPeersEnd);
  383. if (channelsChanged)
  384. {
  385. mCallback();
  386. }
  387. }
  388. template <typename It>
  389. void channelsLeftGateway(const discovery::IpAddress& gatewayAddr,
  390. It channelsBegin,
  391. It channelsEnd)
  392. {
  393. using namespace std;
  394. auto channelsChanged = false;
  395. for (auto byeIt = channelsBegin; byeIt != channelsEnd; ++byeIt)
  396. {
  397. auto bye = *byeIt;
  398. auto it = remove_if(
  399. begin(mChannels),
  400. end(mChannels),
  401. [&](const auto& info)
  402. { return info.gatewayAddr == gatewayAddr && bye == info.channel.id; });
  403. channelsChanged = it != end(mChannels);
  404. mChannels.erase(it, end(mChannels));
  405. mChannelTimeouts.erase(remove_if(begin(mChannelTimeouts),
  406. end(mChannelTimeouts),
  407. [&](const auto& timeout)
  408. {
  409. return std::get<discovery::IpAddress>(timeout)
  410. == gatewayAddr
  411. && std::get<Id>(timeout) == bye;
  412. }),
  413. end(mChannelTimeouts));
  414. }
  415. scheduleNextPruning();
  416. if (channelsChanged)
  417. {
  418. pruneSendHandlers();
  419. mCallback();
  420. }
  421. }
  422. void gatewayClosed(const discovery::IpAddress& gatewayAddr)
  423. {
  424. using namespace std;
  425. auto it =
  426. remove_if(begin(mChannels),
  427. end(mChannels),
  428. [&](const auto& info) { return info.gatewayAddr == gatewayAddr; });
  429. const auto channelsChanged = it != end(mChannels);
  430. mChannels.erase(it, end(mChannels));
  431. mChannelTimeouts.erase(
  432. std::remove_if(
  433. begin(mChannelTimeouts),
  434. end(mChannelTimeouts),
  435. [&](const auto& timeout)
  436. { return std::get<discovery::IpAddress>(timeout) == gatewayAddr; }),
  437. end(mChannelTimeouts));
  438. scheduleNextPruning();
  439. if (channelsChanged)
  440. {
  441. pruneSendHandlers();
  442. mCallback();
  443. }
  444. }
  445. void pruneExpiredChannels()
  446. {
  447. using namespace std;
  448. const auto test = make_tuple(mPruneTimer.now(), discovery::IpAddress{}, Id{});
  449. const auto endExpired = lower_bound(
  450. begin(mChannelTimeouts), end(mChannelTimeouts), test, TimeoutCompare{});
  451. auto channelsChanged = false;
  452. if (endExpired != begin(mChannelTimeouts))
  453. {
  454. channelsChanged = true;
  455. for_each(
  456. begin(mChannelTimeouts),
  457. endExpired,
  458. [&](const auto& timeout)
  459. {
  460. const auto& id = std::get<Id>(timeout);
  461. const auto& gatewayAddr = std::get<discovery::IpAddress>(timeout);
  462. auto it = remove_if(
  463. begin(mChannels),
  464. end(mChannels),
  465. [&](const auto& info)
  466. { return info.channel.id == id && info.gatewayAddr == gatewayAddr; });
  467. mChannels.erase(it, end(mChannels));
  468. });
  469. }
  470. mChannelTimeouts.erase(begin(mChannelTimeouts), endExpired);
  471. scheduleNextPruning();
  472. if (channelsChanged)
  473. {
  474. pruneSendHandlers();
  475. mCallback();
  476. }
  477. }
  478. void scheduleNextPruning()
  479. {
  480. if (!mChannelTimeouts.empty())
  481. {
  482. // Add a second of padding to the timer to avoid over-eager timeouts
  483. const auto t =
  484. std::get<TimePoint>(mChannelTimeouts.front()) + std::chrono::seconds(1);
  485. mPruneTimer.expires_at(t);
  486. mPruneTimer.async_wait(
  487. [this](const TimerError e)
  488. {
  489. if (!e)
  490. {
  491. pruneExpiredChannels();
  492. }
  493. });
  494. }
  495. }
  496. util::Injected<IoContext> mIo;
  497. Callback mCallback;
  498. std::vector<ChannelInfo> mChannels;
  499. struct PeerSendHandler
  500. {
  501. SendHandler handler;
  502. double networkQuality;
  503. };
  504. std::map<Id, PeerSendHandler> mPeerSendHandlers;
  505. using ChannelTimeout = std::tuple<TimePoint, discovery::IpAddress, Id>;
  506. using ChannelTimeouts = std::vector<ChannelTimeout>;
  507. ChannelTimeouts mChannelTimeouts;
  508. Timer mPruneTimer;
  509. };
  510. std::shared_ptr<Impl> mpImpl;
  511. };
  512. } // namespace link_audio
  513. } // namespace ableton