Link.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*! @file Link.hpp
  2. * @copyright 2016, Ableton AG, Berlin. All rights reserved.
  3. * @brief Library for cross-device shared tempo and quantized beat grid
  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. #include <ableton/link/ApiConfig.hpp>
  24. #include <chrono>
  25. #include <mutex>
  26. namespace ableton
  27. {
  28. /*! @class Link and BasicLink
  29. * @brief Classes representing a participant in a Link session.
  30. * The BasicLink type allows to customize the clock. The Link type
  31. * uses the recommended platform-dependent representation of the
  32. * system clock as defined in platforms/Config.hpp.
  33. * It's preferred to use Link instead of BasicLink.
  34. *
  35. * @discussion Each Link instance has its own session state which
  36. * represents a beat timeline and a transport start/stop state. The
  37. * timeline starts running from beat 0 at the initial tempo when
  38. * constructed. The timeline always advances at a speed defined by
  39. * its current tempo, even if transport is stopped. Synchronizing to the
  40. * transport start/stop state of Link is optional for every peer.
  41. * The transport start/stop state is only shared with other peers when
  42. * start/stop synchronization is enabled.
  43. *
  44. * A Link instance is initially disabled after construction, which
  45. * means that it will not communicate on the network. Once enabled,
  46. * a Link instance initiates network communication in an effort to
  47. * discover other peers. When peers are discovered, they immediately
  48. * become part of a shared Link session.
  49. *
  50. * Each method of the Link type documents its thread-safety and
  51. * realtime-safety properties. When a method is marked thread-safe,
  52. * it means it is safe to call from multiple threads
  53. * concurrently. When a method is marked realtime-safe, it means that
  54. * it does not block and is appropriate for use in the thread that
  55. * performs audio IO.
  56. *
  57. * Link provides one session state capture/commit method pair for use
  58. * in the audio thread and one for all other application contexts. In
  59. * general, modifying the session state should be done in the audio
  60. * thread for the most accurate timing results. The ability to modify
  61. * the session state from application threads should only be used in
  62. * cases where an application's audio thread is not actively running
  63. * or if it doesn't generate audio at all. Modifying the Link session
  64. * state from both the audio thread and an application thread
  65. * concurrently is not advised and will potentially lead to unexpected
  66. * behavior.
  67. *
  68. * Only use the BasicLink class if the default platform clock does not
  69. * fulfill other requirements of the client application. Please note this
  70. * will require providing a custom Clock implementation. See the clock()
  71. * documentation for details.
  72. */
  73. template <typename Clock>
  74. class BasicLink
  75. {
  76. public:
  77. class SessionState;
  78. /*! @brief Construct with an initial tempo. */
  79. BasicLink(double bpm);
  80. /*! @brief Link instances cannot be copied or moved */
  81. BasicLink(const BasicLink<Clock>&) = delete;
  82. BasicLink& operator=(const BasicLink<Clock>&) = delete;
  83. BasicLink(BasicLink<Clock>&&) = delete;
  84. BasicLink& operator=(BasicLink<Clock>&&) = delete;
  85. /*! @brief Is Link currently enabled?
  86. * Thread-safe: yes
  87. * Realtime-safe: yes
  88. */
  89. bool isEnabled() const;
  90. /*! @brief Enable/disable Link.
  91. * Thread-safe: yes
  92. * Realtime-safe: no
  93. */
  94. void enable(bool bEnable);
  95. /*! @brief: Is start/stop synchronization enabled?
  96. * Thread-safe: yes
  97. * Realtime-safe: yes
  98. */
  99. bool isStartStopSyncEnabled() const;
  100. /*! @brief: Enable start/stop synchronization.
  101. * Thread-safe: yes
  102. * Realtime-safe: yes
  103. */
  104. void enableStartStopSync(bool bEnable);
  105. /*! @brief How many peers are currently connected in a Link session?
  106. * Thread-safe: yes
  107. * Realtime-safe: yes
  108. */
  109. std::size_t numPeers() const;
  110. /*! @brief Register a callback to be notified when the number of
  111. * peers in the Link session changes.
  112. * Thread-safe: yes
  113. * Realtime-safe: no
  114. *
  115. * @discussion The callback is invoked on a Link-managed thread.
  116. *
  117. * @param callback The callback signature is:
  118. * void (std::size_t numPeers)
  119. */
  120. template <typename Callback>
  121. void setNumPeersCallback(Callback callback);
  122. /*! @brief Register a callback to be notified when the session
  123. * tempo changes.
  124. * Thread-safe: yes
  125. * Realtime-safe: no
  126. *
  127. * @discussion The callback is invoked on a Link-managed thread.
  128. *
  129. * @param callback The callback signature is: void (double bpm)
  130. */
  131. template <typename Callback>
  132. void setTempoCallback(Callback callback);
  133. /*! brief: Register a callback to be notified when the state of
  134. * start/stop isPlaying changes.
  135. * Thread-safe: yes
  136. * Realtime-safe: no
  137. *
  138. * @discussion The callback is invoked on a Link-managed thread.
  139. *
  140. * @param callback The callback signature is:
  141. * void (bool isPlaying)
  142. */
  143. template <typename Callback>
  144. void setStartStopCallback(Callback callback);
  145. /*! @brief The clock used by Link.
  146. * Thread-safe: yes
  147. * Realtime-safe: yes
  148. *
  149. * @discussion The Clock type is a platform-dependent representation
  150. * of the system clock. It exposes a micros() method, which is a
  151. * normalized representation of the current system time in
  152. * std::chrono::microseconds.
  153. */
  154. Clock clock() const;
  155. /*! @brief Capture the current Link Session State from the audio thread.
  156. * Thread-safe: no
  157. * Realtime-safe: yes
  158. *
  159. * @discussion This method should ONLY be called in the audio thread
  160. * and must not be accessed from any other threads. The returned
  161. * object stores a snapshot of the current Link Session State, so it
  162. * should be captured and used in a local scope. Storing the
  163. * Session State for later use in a different context is not advised
  164. * because it will provide an outdated view.
  165. */
  166. SessionState captureAudioSessionState() const;
  167. /*! @brief Commit the given Session State to the Link session from the
  168. * audio thread.
  169. * Thread-safe: no
  170. * Realtime-safe: yes
  171. *
  172. * @discussion This method should ONLY be called in the audio
  173. * thread. The given Session State will replace the current Link
  174. * state. Modifications will be communicated to other peers in the
  175. * session.
  176. */
  177. void commitAudioSessionState(SessionState state);
  178. /*! @brief Capture the current Link Session State from an application
  179. * thread.
  180. * Thread-safe: yes
  181. * Realtime-safe: no
  182. *
  183. * @discussion Provides a mechanism for capturing the Link Session
  184. * State from an application thread (other than the audio thread).
  185. * The returned Session State stores a snapshot of the current Link
  186. * state, so it should be captured and used in a local scope.
  187. * Storing the it for later use in a different context is not
  188. * advised because it will provide an outdated view.
  189. */
  190. SessionState captureAppSessionState() const;
  191. /*! @brief Commit the given Session State to the Link session from an
  192. * application thread.
  193. * Thread-safe: yes
  194. * Realtime-safe: no
  195. *
  196. * @discussion The given Session State will replace the current Link
  197. * Session State. Modifications of the Session State will be
  198. * communicated to other peers in the session.
  199. */
  200. void commitAppSessionState(SessionState state);
  201. /*! @class SessionState
  202. * @brief Representation of a timeline and the start/stop state
  203. *
  204. * @discussion A SessionState object is intended for use in a local scope within
  205. * a single thread - none of its methods are thread-safe. All of its methods are
  206. * non-blocking, so it is safe to use from a realtime thread.
  207. * It provides functions to observe and manipulate the timeline and start/stop
  208. * state.
  209. *
  210. * The timeline is a representation of a mapping between time and beats for varying
  211. * quanta.
  212. * The start/stop state represents the user intention to start or stop transport at
  213. * a specific time. Start stop synchronization is an optional feature that allows to
  214. * share the user request to start or stop transport between a subgroup of peers in
  215. * a Link session. When observing a change of start/stop state, audio playback of a
  216. * peer should be started or stopped the same way it would have happened if the user
  217. * had requested that change at the according time locally. The start/stop state can
  218. * only be changed by the user. This means that the current local start/stop state
  219. * persists when joining or leaving a Link session. After joining a Link session
  220. * start/stop change requests will be communicated to all connected peers.
  221. */
  222. class SessionState
  223. {
  224. public:
  225. SessionState(const link::ApiState state, const bool bRespectQuantum);
  226. bool operator==(const SessionState& other) const;
  227. bool operator!=(const SessionState& other) const;
  228. /*! @brief: The tempo of the timeline, in Beats Per Minute.
  229. *
  230. * @discussion This is a stable value that is appropriate for display
  231. * to the user. Beat time progress will not necessarily match this tempo
  232. * exactly because of clock drift compensation.
  233. */
  234. double tempo() const;
  235. /*! @brief: Set the timeline tempo to the given bpm value, taking
  236. * effect at the given time.
  237. */
  238. void setTempo(double bpm, std::chrono::microseconds atTime);
  239. /*! @brief: Get the beat value corresponding to the given time
  240. * for the given quantum.
  241. *
  242. * @discussion: The magnitude of the resulting beat value is
  243. * unique to this Link instance, but its phase with respect to
  244. * the provided quantum is shared among all session
  245. * peers. For non-negative beat values, the following
  246. * property holds: fmod(beatAtTime(t, q), q) == phaseAtTime(t, q)
  247. */
  248. double beatAtTime(std::chrono::microseconds time, double quantum) const;
  249. /*! @brief: Get the session phase at the given time for the given
  250. * quantum.
  251. *
  252. * @discussion: The result is in the interval [0, quantum). The
  253. * result is equivalent to fmod(beatAtTime(t, q), q) for
  254. * non-negative beat values. This method is convenient if the
  255. * client is only interested in the phase and not the beat
  256. * magnitude. Also, unlike fmod, it handles negative beat values
  257. * correctly.
  258. */
  259. double phaseAtTime(std::chrono::microseconds time, double quantum) const;
  260. /*! @brief: Get the time at which the given beat occurs for the
  261. * given quantum.
  262. *
  263. * @discussion: The inverse of beatAtTime, assuming a constant
  264. * tempo. beatAtTime(timeAtBeat(b, q), q) === b.
  265. */
  266. std::chrono::microseconds timeAtBeat(double beat, double quantum) const;
  267. /*! @brief: Attempt to map the given beat to the given time in the
  268. * context of the given quantum.
  269. *
  270. * @discussion: This method behaves differently depending on the
  271. * state of the session. If no other peers are connected,
  272. * then this instance is in a session by itself and is free to
  273. * re-map the beat/time relationship whenever it pleases. In this
  274. * case, beatAtTime(time, quantum) == beat after this method has
  275. * been called.
  276. *
  277. * If there are other peers in the session, this instance
  278. * should not abruptly re-map the beat/time relationship in the
  279. * session because that would lead to beat discontinuities among
  280. * the other peers. In this case, the given beat will be mapped
  281. * to the next time value greater than the given time with the
  282. * same phase as the given beat.
  283. *
  284. * This method is specifically designed to enable the concept of
  285. * "quantized launch" in client applications. If there are no other
  286. * peers in the session, then an event (such as starting
  287. * transport) happens immediately when it is requested. If there
  288. * are other peers, however, we wait until the next time at which
  289. * the session phase matches the phase of the event, thereby
  290. * executing the event in-phase with the other peers in the
  291. * session. The client only needs to invoke this method to
  292. * achieve this behavior and should not need to explicitly check
  293. * the number of peers.
  294. */
  295. void requestBeatAtTime(double beat, std::chrono::microseconds time, double quantum);
  296. /*! @brief: Rudely re-map the beat/time relationship for all peers
  297. * in a session.
  298. *
  299. * @discussion: DANGER: This method should only be needed in
  300. * certain special circumstances. Most applications should not
  301. * use it. It is very similar to requestBeatAtTime except that it
  302. * does not fall back to the quantizing behavior when it is in a
  303. * session with other peers. Calling this method will
  304. * unconditionally map the given beat to the given time and
  305. * broadcast the result to the session. This is very anti-social
  306. * behavior and should be avoided.
  307. *
  308. * One of the few legitimate uses of this method is to
  309. * synchronize a Link session with an external clock source. By
  310. * periodically forcing the beat/time mapping according to an
  311. * external clock source, a peer can effectively bridge that
  312. * clock into a Link session. Much care must be taken at the
  313. * application layer when implementing such a feature so that
  314. * users do not accidentally disrupt Link sessions that they may
  315. * join.
  316. */
  317. void forceBeatAtTime(double beat, std::chrono::microseconds time, double quantum);
  318. /*! @brief: Set if transport should be playing or stopped, taking effect
  319. * at the given time.
  320. */
  321. void setIsPlaying(bool isPlaying, std::chrono::microseconds time);
  322. /*! @brief: Is transport playing? */
  323. bool isPlaying() const;
  324. /*! @brief: Get the time at which a transport start/stop occurs */
  325. std::chrono::microseconds timeForIsPlaying() const;
  326. /*! @brief: Convenience function to attempt to map the given beat to the time
  327. * when transport is starting to play in context of the given quantum.
  328. * This function evaluates to a no-op if isPlaying() equals false.
  329. */
  330. void requestBeatAtStartPlayingTime(double beat, double quantum);
  331. /*! @brief: Convenience function to start or stop transport at a given time and
  332. * attempt to map the given beat to this time in context of the given quantum.
  333. */
  334. void setIsPlayingAndRequestBeatAtTime(bool isPlaying,
  335. std::chrono::microseconds time,
  336. double beat,
  337. double quantum);
  338. private:
  339. template <typename SessionState>
  340. friend const link::ApiState& detail::linkApiState(const SessionState& sessionState);
  341. friend BasicLink<Clock>;
  342. link::ApiState mOriginalState;
  343. link::ApiState mState;
  344. bool mbRespectQuantum;
  345. };
  346. protected:
  347. using Controller = ableton::link::ApiController<Clock>;
  348. std::mutex mCallbackMutex;
  349. link::PeerCountCallback mPeerCountCallback = [](std::size_t) {};
  350. link::TempoCallback mTempoCallback = [](link::Tempo) {};
  351. link::StartStopStateCallback mStartStopCallback = [](bool) {};
  352. Clock mClock;
  353. Controller mController;
  354. };
  355. class Link : public BasicLink<link::platform::Clock>
  356. {
  357. public:
  358. using Clock = link::platform::Clock;
  359. Link(double bpm)
  360. : BasicLink(bpm)
  361. {
  362. }
  363. };
  364. } // namespace ableton
  365. #include <ableton/Link.ipp>