Controller.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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/Controller.hpp>
  22. #include <ableton/link_audio/Channels.hpp>
  23. #include <ableton/link_audio/Id.hpp>
  24. #include <ableton/link_audio/MainProcessor.hpp>
  25. #include <ableton/link_audio/PeerGateways.hpp>
  26. #include <ableton/link_audio/PeerInfo.hpp>
  27. #include <ableton/link_audio/UdpMessenger.hpp>
  28. #include <ableton/util/Injected.hpp>
  29. #include <ableton/util/Locked.hpp>
  30. #include <algorithm>
  31. #include <atomic>
  32. #include <functional>
  33. #include <optional>
  34. #include <set>
  35. #include <vector>
  36. namespace ableton
  37. {
  38. namespace link_audio
  39. {
  40. using ChannelsChangedCallback = std::function<void()>;
  41. using CallOnThreadFunction = std::function<void()>;
  42. template <typename PeerCountCallback,
  43. typename TempoCallback,
  44. typename StartStopStateCallback,
  45. typename Clock,
  46. typename Random,
  47. typename IoContext,
  48. typename SessionController>
  49. class Controller : public link::Controller<PeerCountCallback,
  50. TempoCallback,
  51. StartStopStateCallback,
  52. Clock,
  53. Random,
  54. IoContext,
  55. SessionController>
  56. {
  57. public:
  58. using LinkController = link::Controller<PeerCountCallback,
  59. TempoCallback,
  60. StartStopStateCallback,
  61. Clock,
  62. Random,
  63. IoContext,
  64. SessionController>;
  65. Controller(link::Tempo tempo,
  66. link::PeerCountCallback peerCallback,
  67. link::TempoCallback tempoCallback,
  68. link::StartStopStateCallback startStopStateCallback,
  69. Clock clock)
  70. : LinkController(tempo, peerCallback, tempoCallback, startStopStateCallback, clock)
  71. , mChannelsChangedCallback{[]() {}}
  72. , mApiChannels({})
  73. , mIsLinkAudioEnabledByUser(false)
  74. , mIsLinkAudioEffectivlyEnabled(false)
  75. , mPeerInfo({})
  76. , mChannels(util::injectRef(*(this->mIo)), ChannelsChanged{this})
  77. , mProcessor{util::injectRef(*(this->mIo)), util::injectVal(ChannelsCallback{this})}
  78. , mGateways{util::injectVal(GatewayFactory{this}), util::injectRef(*(this->mIo))}
  79. {
  80. }
  81. void enableLinkAudio(bool enabled)
  82. {
  83. mIsLinkAudioEnabledByUser = enabled;
  84. this->mRtClientStateSetter.invoke();
  85. }
  86. bool isLinkAudioEnabled() const { return mIsLinkAudioEnabledByUser; }
  87. std::string name() const { return mPeerInfo.read().name; }
  88. void setName(std::string name)
  89. {
  90. this->mIo->async(
  91. [this, name = std::move(name)]()
  92. {
  93. mPeerInfo.update([&, name = std::move(name)](auto& pi)
  94. { pi.name = std::move(name); });
  95. if (this->mpSessionController)
  96. {
  97. this->mpSessionController->updateDiscoveryCallback();
  98. }
  99. });
  100. }
  101. void callOnLinkThread(CallOnThreadFunction func)
  102. {
  103. this->mIo->async([func = std::move(func)]() { func(); });
  104. }
  105. SharedSink addSink(std::string name, size_t maxNumSamples)
  106. {
  107. auto id = Id::random<Random>();
  108. auto sink = std::make_shared<Sink>(name, maxNumSamples, id);
  109. this->mIo->async(
  110. [this, sink]()
  111. {
  112. this->mProcessor.addSink(
  113. sink, util::injectVal(GetSender{this}), util::injectVal(GetNodeId{this}));
  114. if (this->mpSessionController)
  115. {
  116. this->mpSessionController->updateDiscoveryCallback();
  117. }
  118. });
  119. return sink;
  120. }
  121. SharedSource addSource(Id channelId, Source::Callback callback)
  122. {
  123. auto source = std::make_shared<Source>(std::move(channelId), std::move(callback));
  124. this->mIo->async(
  125. [this, source]()
  126. {
  127. mProcessor.addSource(
  128. source, util::injectVal(GetSender{this}), util::injectVal(GetNodeId{this}));
  129. });
  130. return source;
  131. }
  132. void setChannelsChangedCallback(ChannelsChangedCallback callback)
  133. {
  134. this->mIo->async([&, callback = std::move(callback)]()
  135. { mChannelsChangedCallback = callback; });
  136. }
  137. auto channels() const { return mApiChannels.read(); }
  138. protected:
  139. void updateIsLinkAudioEnabled()
  140. {
  141. const auto shouldBeEnabled = this->mEnabled && mIsLinkAudioEnabledByUser;
  142. if (shouldBeEnabled && !mIsLinkAudioEffectivlyEnabled)
  143. {
  144. mIsLinkAudioEffectivlyEnabled = true;
  145. this->mpSessionController->gatewaysChangedCallback();
  146. }
  147. else if (!shouldBeEnabled && mIsLinkAudioEffectivlyEnabled)
  148. {
  149. mIsLinkAudioEffectivlyEnabled = false;
  150. mGateways.clear();
  151. }
  152. }
  153. void updateAudioDiscovery()
  154. {
  155. mGateways.updateAnnouncement(PeerAnnouncement{this->mNodeId,
  156. this->mSessionId,
  157. mPeerInfo.read(),
  158. mProcessor.channelAnnouncements()});
  159. }
  160. void updateLinkAudio()
  161. {
  162. auto peers = std::set<link::NodeId>();
  163. for (const auto& sessionPeer : this->mPeers.sessionPeers(this->mSessionId))
  164. {
  165. peers.insert(sessionPeer.first.nodeState.ident());
  166. }
  167. mGateways.updateSessionPeers(begin(peers), end(peers));
  168. // Remove channels for peers that are no longer in the session
  169. mChannels.prunePeerChannels(peers.begin(), peers.end());
  170. updateApiChannels();
  171. }
  172. void sawLinkAudioEndpoint(link::NodeId peerId,
  173. std::optional<discovery::UdpEndpoint> endpoint,
  174. discovery::IpAddress gateway)
  175. {
  176. mGateways.sawLinkAudioEndpoint(peerId, endpoint, gateway);
  177. }
  178. void updateLinkAudioGateways()
  179. {
  180. auto gateways = std::vector<discovery::IpAddress>();
  181. this->mDiscovery.withGateways(
  182. [&](auto begin, auto end)
  183. { std::for_each(begin, end, [&](auto& it) { gateways.push_back(it.first); }); });
  184. if (mIsLinkAudioEffectivlyEnabled)
  185. {
  186. mGateways.updateGateways(std::move(gateways));
  187. updateLinkAudio();
  188. }
  189. else
  190. {
  191. mGateways.clear();
  192. }
  193. }
  194. void updateAudioEndpoints(std::vector<discovery::UdpEndpoint> endpoints)
  195. {
  196. this->mDiscovery.withGateways(
  197. [&](auto begin, auto end)
  198. {
  199. std::for_each(begin,
  200. end,
  201. [&](auto& gateway)
  202. {
  203. auto it = std::find_if(endpoints.begin(),
  204. endpoints.end(),
  205. [&](const auto& ep)
  206. { return ep.address() == gateway.first; });
  207. if (it != endpoints.end())
  208. {
  209. gateway.second->updateAudioEndpoint(*it);
  210. }
  211. else
  212. {
  213. gateway.second->updateAudioEndpoint(std::nullopt);
  214. }
  215. });
  216. });
  217. this->updateDiscovery();
  218. }
  219. void updateApiChannels()
  220. {
  221. auto channelsChanged = false;
  222. auto currentChannels = mChannels.uniqueSessionChannels(this->mSessionId);
  223. std::sort(currentChannels.begin(),
  224. currentChannels.end(),
  225. [](const auto& a, const auto& b)
  226. {
  227. if (a.peerName == b.peerName)
  228. {
  229. return a.name < b.name;
  230. }
  231. return a.peerName < b.peerName;
  232. });
  233. mApiChannels.update(
  234. [&](auto& apiChannels)
  235. {
  236. if (apiChannels != currentChannels)
  237. {
  238. apiChannels = currentChannels;
  239. channelsChanged = true;
  240. }
  241. });
  242. if (channelsChanged)
  243. {
  244. mChannelsChangedCallback();
  245. }
  246. }
  247. struct ChannelsChanged
  248. {
  249. void operator()() { mpController->updateApiChannels(); }
  250. Controller* mpController;
  251. };
  252. using Interface = MessengerInterface<typename util::Injected<IoContext>::type&>;
  253. using ControllerChannels = Channels<IoContext&, ChannelsChanged, Interface>;
  254. using SendHandler = typename ControllerChannels::SendHandler;
  255. struct GetSender
  256. {
  257. std::optional<SendHandler> forChannel(const Id& id)
  258. {
  259. return mpController->mChannels.channelSendHandler(id);
  260. }
  261. std::optional<SendHandler> forPeer(const Id& id)
  262. {
  263. return mpController->mChannels.peerSendHandler(id);
  264. }
  265. Controller* mpController;
  266. };
  267. struct GetNodeId
  268. {
  269. const link::NodeId& operator()() const { return mpController->mNodeId; }
  270. Controller* mpController;
  271. };
  272. struct ChannelsCallback
  273. {
  274. void operator()()
  275. {
  276. if (mpController && mpController->mpSessionController)
  277. {
  278. mpController->mpSessionController->updateDiscoveryCallback();
  279. }
  280. }
  281. Controller* mpController;
  282. };
  283. using ControllerMainProcessor =
  284. MainProcessor<ChannelsCallback, GetSender, GetNodeId, Random, IoContext&>;
  285. using ControllerMessengerPtr =
  286. MessengerPtr<ControllerMainProcessor&,
  287. typename ControllerChannels::GatewayObserver,
  288. typename util::Injected<IoContext>::type&>;
  289. struct GatewayFactory
  290. {
  291. ControllerMessengerPtr operator()(const discovery::IpAddress& addr)
  292. {
  293. return makeMessengerPtr(
  294. util::injectRef(mpController->mProcessor),
  295. util::injectRef(*(mpController->mIo)),
  296. addr,
  297. util::injectVal(makeGatewayObserver(mpController->mChannels, addr)),
  298. PeerAnnouncement{mpController->mNodeId,
  299. mpController->mSessionId,
  300. mpController->mPeerInfo.read(),
  301. mpController->mProcessor.channelAnnouncements()});
  302. }
  303. void gatewaysChanged()
  304. {
  305. std::vector<discovery::UdpEndpoint> endpoints;
  306. mpController->mGateways.withGateways(
  307. [&](auto begin, auto end)
  308. {
  309. endpoints.reserve(std::distance(begin, end));
  310. std::transform(begin,
  311. end,
  312. std::back_inserter(endpoints),
  313. [](auto gateway) { return gateway.second->endpoint(); });
  314. });
  315. mpController->updateAudioEndpoints(std::move(endpoints));
  316. }
  317. Controller* mpController;
  318. };
  319. void stopAudio()
  320. {
  321. mIsLinkAudioEnabledByUser = false;
  322. updateIsLinkAudioEnabled();
  323. mProcessor.stop();
  324. }
  325. ChannelsChangedCallback mChannelsChangedCallback;
  326. util::Locked<std::vector<typename ControllerChannels::Channel>> mApiChannels;
  327. std::atomic_bool mIsLinkAudioEnabledByUser;
  328. bool mIsLinkAudioEffectivlyEnabled;
  329. util::Locked<PeerInfo> mPeerInfo;
  330. ControllerChannels mChannels;
  331. ControllerMainProcessor mProcessor;
  332. PeerGateways<GatewayFactory, IoContext&> mGateways;
  333. };
  334. } // namespace link_audio
  335. } // namespace ableton