LinkAudio.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /*! @file LinkAudio.hpp
  2. * @copyright 2025, Ableton AG, Berlin. All rights reserved.
  3. * @brief Library for cross-device shared tempo, quantized beat grid, and sharing audio
  4. *
  5. * @license:
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. * If you would like to incorporate Link into a proprietary software application,
  20. * please contact <link-devs@ableton.com>.
  21. */
  22. #pragma once
  23. #define LINK_AUDIO YES
  24. #include <ableton/link_audio/ApiConfig.hpp>
  25. #include <memory>
  26. #include <optional>
  27. #include <string>
  28. #include <vector>
  29. namespace ableton
  30. {
  31. /*! @class LinkAudio and BasicLinkAudio
  32. * @brief LinkAudio provides the Link functionality plus audio sharing.
  33. * To enable audio sharing include this header and replace the Link class with the
  34. * LinkAudio and Link should not be used simultaneously.
  35. *
  36. * @discussion
  37. * LinkAudio provides the same functionality as Link. See Link.hpp for the respective
  38. * documentation. On top of that, LinkAudio allows to announce and discover audio
  39. * channels in a Link session. When sending and receiving audio, the Link beat time grid
  40. * and quantum can be used to align audio from different peers.
  41. *
  42. * Channels in a Link session are represented as sinks on the sending side and sources on
  43. * the receiving side.
  44. * Sinks only send audio if at least one corresponding source is present in the session.
  45. * Audio buffers are interleaved and samples are represented as 16-bit signed integers.
  46. */
  47. template <typename Clock>
  48. class BasicLinkAudio : public BasicLink<Clock>
  49. {
  50. public:
  51. /*! @brief Construct with an initial tempo and local peer name for identification in the
  52. * Link session. Names longer than 256 characters will be truncated.
  53. */
  54. BasicLinkAudio(double bpm, std::string name);
  55. ~BasicLinkAudio();
  56. /*! @brief Is audio currently enabled?
  57. * Thread-safe: yes
  58. * Realtime-safe: yes
  59. */
  60. bool isLinkAudioEnabled() const;
  61. /*! @brief Enable or disable audio.
  62. * Thread-safe: yes
  63. * Realtime-safe: no
  64. */
  65. void enableLinkAudio(bool bEnable);
  66. /*! @brief Get the local peer name for identification in the Link session.
  67. * Thread-safe: yes
  68. * Realtime-safe: no
  69. */
  70. std::string peerName() const;
  71. /*! @brief Change the local peer name for identification in the Link session.
  72. * Names longer than 256 characters will be truncated.
  73. * Thread-safe: yes
  74. * Realtime-safe: no
  75. */
  76. void setPeerName(std::string name);
  77. /*! @brief Register a callback to be notified when the set of available
  78. * audio channels changes. This will be called when channels are discovered or
  79. * disappeared and when names change.
  80. * Thread-safe: yes
  81. * Realtime-safe: no
  82. *
  83. * @discussion The callback is invoked on a Link-managed thread.
  84. * @param callback The callback signature is: void ()
  85. */
  86. template <typename Callback>
  87. void setChannelsChangedCallback(Callback callback);
  88. /*! @struct Channel
  89. * @brief Describes an audio channel available in the Link session.
  90. * @discussion
  91. * The unique identifiers for channels and peers are persistent for the lifetime of a
  92. * channel. Names may change over time and are meant for display purposes.
  93. */
  94. struct Channel
  95. {
  96. ChannelId id; /*!< Unique identifier for the channel. */
  97. std::string name; /*!< Name of the channel. */
  98. PeerId peerId; /*!< Identifier of the peer providing the channel. */
  99. std::string peerName; /*!< Name of the peer providing the channel. */
  100. };
  101. /*! @brief Get the list of currently available audio channels in the session.
  102. * Thread-safe: yes
  103. * Realtime-safe: no
  104. */
  105. std::vector<Channel> channels() const;
  106. /*! @brief Call a function on the Link thread.
  107. * Thread-safe: yes
  108. * Realtime-safe: no
  109. *
  110. * @discussion The function will be called on the Link thread, which is managed by the
  111. * LinkAudio instance. This is useful for setting the thread priority for example.
  112. * @param func The function signature is: void ()
  113. */
  114. template <typename Function>
  115. void callOnLinkThread(Function func);
  116. private:
  117. using Controller = ableton::link::ApiController<Clock>;
  118. link_audio::ChannelsChangedCallback mChannelsChangedCallback = []() {};
  119. };
  120. class LinkAudio : public BasicLinkAudio<link::platform::Clock>
  121. {
  122. public:
  123. using Clock = link::platform::Clock;
  124. LinkAudio(double bpm, std::string name)
  125. : BasicLinkAudio<Clock>(bpm, name)
  126. {
  127. }
  128. private:
  129. friend class LinkAudioSink;
  130. friend class LinkAudioSource;
  131. };
  132. /*! @class LinkAudioSink
  133. * @brief Announces an audio channel to the Link session.
  134. *
  135. * @discussion
  136. * The announced channel is visible to other peers for the lifetime of the sink.
  137. * The sink can be used to write audio samples, which will be sent to peers that have
  138. * respective sources.
  139. */
  140. class LinkAudioSink
  141. {
  142. public:
  143. /*! @brief Construct a LinkAudioSink with a LinkAudio instance, a name of the audio
  144. * channel, and the maximum buffer size in samples. This buffer size should account for
  145. * the number of channels times the number of samples per channel in one audio
  146. * callback. Names longer than 256 characters will be truncated.
  147. */
  148. template <typename LinkAudio>
  149. LinkAudioSink(LinkAudio& link, std::string name, size_t maxNumSamples);
  150. LinkAudioSink(const LinkAudioSink&) = default;
  151. LinkAudioSink& operator=(const LinkAudioSink&) = default;
  152. LinkAudioSink(LinkAudioSink&&) = default;
  153. LinkAudioSink& operator=(LinkAudioSink&&) = default;
  154. /*! @brief Get the name of the channel.
  155. * Thread-safe: no
  156. * Realtime-safe: no
  157. */
  158. std::string name() const;
  159. /*! @brief Set the name of this channel. Names longer than 256 characters will be
  160. * truncated.
  161. * Thread-safe: no
  162. * Realtime-safe: no
  163. */
  164. void setName(std::string name);
  165. /*! @brief Request a maximum buffer size for future buffers.
  166. * Thread-safe: yes
  167. * Realtime-safe: yes
  168. *
  169. * @discussion Increase the number of samples retained buffer handles can hold. If the
  170. * requested number of samples is smaller than the current maximum number of samples
  171. * this is a no-op.
  172. */
  173. void requestMaxNumSamples(size_t numSamples);
  174. /*! @brief Get the current maximum number of samples a buffer handle can hold.
  175. * Thread-safe: yes
  176. * Realtime-safe: yes
  177. */
  178. size_t maxNumSamples() const;
  179. /*! @struct BufferHandle
  180. * @brief Handle to a buffer for writing audio samples.
  181. */
  182. struct BufferHandle
  183. {
  184. /*! @brief Retain a buffer for writing audio samples. Only on BufferHandle can be
  185. * retained at a time. A BufferHandle should never outlive the LinkAudioSink it was
  186. * created from.
  187. * Thread-safe: no
  188. * Realtime-safe: yes
  189. */
  190. BufferHandle(LinkAudioSink&);
  191. BufferHandle(const BufferHandle&) = delete;
  192. BufferHandle(BufferHandle&& other) = delete;
  193. BufferHandle& operator=(const BufferHandle&) = delete;
  194. BufferHandle& operator=(BufferHandle&& other) = delete;
  195. ~BufferHandle();
  196. /*! @brief Check if the handle is valid. Make sure to check this before
  197. * using the handle. The handle may be invalid if no corresponding source exists or
  198. * no buffer is available.
  199. *
  200. * Thread-safe: no
  201. * Realtime-safe: yes
  202. */
  203. operator bool() const;
  204. int16_t* samples; /*!< Pointer to the buffer for writing samples. */
  205. size_t maxNumSamples; /*!< Maximum number of samples that can be written. */
  206. /*! @brief Commit the buffer after writing samples. After this the buffer the object
  207. * should not be used anymore.
  208. * @param sessionState The current Link session state.
  209. * @param beatsAtBufferBegin Beat at the start of the buffer.
  210. * @param quantum Quantum value for beat mapping.
  211. * @param numFrames Number of frames written. numFrames * numChannels may not exceed
  212. * maxNumSamples.
  213. * @param numChannels Number of channels. Can be 1 for mono or 2 for stereo.
  214. * @param sampleRate Sample rate in Hz. Must be greater than 0.
  215. * @return True if the buffer was successfully committed.
  216. *
  217. * Thread-safe: no
  218. * Realtime-safe: yes
  219. *
  220. * @discussion The Link session state, the quantum, and the beats at buffer begin
  221. * must be same as used for rendering the audio locally. Changes to the Link session
  222. * state should always be made before rendering and eventually writing the buffer.
  223. */
  224. template <typename SessionState>
  225. bool commit(const SessionState&,
  226. double beatsAtBufferBegin,
  227. double quantum,
  228. size_t numFrames,
  229. size_t numChannels,
  230. uint32_t sampleRate);
  231. private:
  232. std::weak_ptr<link_audio::Sink> mpSink;
  233. link_audio::Buffer<int16_t>* mpBuffer;
  234. };
  235. private:
  236. friend struct BufferHandle;
  237. std::shared_ptr<link_audio::Sink> mpImpl;
  238. };
  239. /*! @class LinkAudioSource
  240. * @brief Receives audio streams from other peers in the Link session.
  241. *
  242. * @discussion
  243. * LinkAudioSource allows an application to subscribe to an audio channel
  244. * published by another peer, receiving buffers as they become available.
  245. */
  246. class LinkAudioSource
  247. {
  248. public:
  249. struct BufferHandle;
  250. /*! @brief Construct a LinkAudioSource to receive audio for a specifc channel.
  251. * @param link The LinkAudio instance.
  252. * @param id The ID of the channel to be received.
  253. * @param callback Callback invoked on a Link-managed thread when a buffer is received.
  254. * The callback signature is: void (BufferHandle bufferHandle)
  255. */
  256. template <typename LinkAudio, typename Callback>
  257. LinkAudioSource(LinkAudio& link, ChannelId id, Callback callback);
  258. LinkAudioSource(const LinkAudioSource&) = default;
  259. LinkAudioSource& operator=(const LinkAudioSource&) = default;
  260. LinkAudioSource(LinkAudioSource&&) = default;
  261. LinkAudioSource& operator=(LinkAudioSource&&) = default;
  262. ~LinkAudioSource();
  263. /*! @brief Get the channel ID of the corresponding source.
  264. * Thread-safe: yes
  265. * Realtime-safe: yes
  266. */
  267. ChannelId id() const;
  268. /*! @struct BufferHandle
  269. * @brief Handle to a buffer containing received audio samples.
  270. */
  271. struct BufferHandle
  272. {
  273. /*! @struct Info
  274. * @brief Metadata about the received audio buffer.
  275. */
  276. struct Info
  277. {
  278. size_t numChannels; /*!< Number of channels in the buffer. */
  279. size_t numFrames; /*!< Number of frames in the buffer. */
  280. uint32_t sampleRate; /*!< Sample rate in Hz. */
  281. uint64_t count; /*!< Sequence number of the buffer. */
  282. double sessionBeatTime; /*!< Use beginBeats() to map this to local beat time. */
  283. double tempo; /*!< Tempo in beats per minute. */
  284. SessionId sessionId; /*!< ID of the session the buffer belongs to. */
  285. /*! @brief Map the beat time at the begin of the buffer to the local Link session
  286. * state.
  287. * @param sessionState The current Link session state.
  288. * @param quantum Quantum value for beat mapping.
  289. * @return Local beat time at buffer begin. Returns nullopt if the buffer
  290. * originates from a different Link Session.
  291. */
  292. template <typename SessionState>
  293. std::optional<double> beginBeats(const SessionState&, double quantum) const;
  294. /*! @brief Map the beat time at the end of the buffer to the local Link session
  295. * state.
  296. * @param sessionState The current Link session state.
  297. * @param quantum Quantum value for beat mapping.
  298. * @return Local beat time at buffer end. Returns nullopt if the buffer
  299. * originates from a different Link Session.
  300. */
  301. template <typename SessionState>
  302. std::optional<double> endBeats(const SessionState&, double quantum) const;
  303. };
  304. int16_t* samples; /*!< Pointer to the buffer of received samples. */
  305. Info info; /*!< Information about the buffer. */
  306. };
  307. private:
  308. std::shared_ptr<link_audio::Source> mpImpl;
  309. };
  310. } // namespace ableton
  311. #include <ableton/LinkAudio.ipp>