link-Link-1.0.0/0000755000175000017500000000000012765602651013604 5ustar zmoelnigzmoelniglink-Link-1.0.0/AbletonLinkConfig.cmake0000644000175000017500000000267512765602651020150 0ustar zmoelnigzmoelnigif(CMAKE_VERSION VERSION_LESS 3.0) message(FATAL_ERROR "CMake 3.0 or greater is required") endif() add_library(Ableton::Link IMPORTED INTERFACE) set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_LIST_DIR}/include ) # Force C++11 support for consuming targets set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_COMPILE_FEATURES cxx_generalized_initializers ) if(UNIX) set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS LINK_PLATFORM_UNIX=1 ) endif() if(APPLE) set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS LINK_PLATFORM_MACOSX=1 ) elseif(WIN32) set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS LINK_PLATFORM_WINDOWS=1 ) set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_COMPILE_OPTIONS "/wd4503" # 'Identifier': decorated name length exceeded, name was truncated ) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS LINK_PLATFORM_LINUX=1 ) endif() include(${CMAKE_CURRENT_LIST_DIR}/cmake_include/AsioStandaloneConfig.cmake) set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_LINK_LIBRARIES AsioStandalone::AsioStandalone ) set_property(TARGET Ableton::Link APPEND PROPERTY INTERFACE_SOURCES ${CMAKE_CURRENT_LIST_DIR}/include/ableton/Link.hpp ) link-Link-1.0.0/CMakeLists.txt0000644000175000017500000000400412765602651016342 0ustar zmoelnigzmoelnigcmake_minimum_required(VERSION 3.0) project(Link) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) # ___ _ _ # / _ \ _ __ | |_(_) ___ _ __ ___ # | | | | '_ \| __| |/ _ \| '_ \/ __| # | |_| | |_) | |_| | (_) | | | \__ \ # \___/| .__/ \__|_|\___/|_| |_|___/ # |_| # Note: Please use the LINK_* prefix for all project-specific options option(LINK_BUILD_QT_EXAMPLES "Build examples (Requires Qt)" OFF) if(UNIX) set(LINK_WORD_SIZE "64" CACHE STRING "Set the word size (must be either 32 or 64)") option(LINK_ENABLE_ASAN "Build with Address Sanitizier (ASan)" OFF) endif() if(WIN32) if(${CMAKE_GENERATOR} MATCHES "Win64") set(LINK_WORD_SIZE "64") else() set(LINK_WORD_SIZE "32") endif() option(LINK_BUILD_ASIO "Build example applications with ASIO driver" ON) option(LINK_BUILD_VLD "Build with VLD support (VLD must be installed separately)" OFF) endif() # ____ _ _ # | _ \ __ _| |_| |__ ___ # | |_) / _` | __| '_ \/ __| # | __/ (_| | |_| | | \__ \ # |_| \__,_|\__|_| |_|___/ # # Other CMake files must be included only after declaring build options include(cmake_include/ConfigureCompileFlags.cmake) include(cmake_include/ConfigureWordSize.cmake) include(cmake_include/CatchConfig.cmake) include(AbletonLinkConfig.cmake) add_subdirectory(include) add_subdirectory(src) add_subdirectory(examples) # ____ # / ___| _ _ _ __ ___ _ __ ___ __ _ _ __ _ _ # \___ \| | | | '_ ` _ \| '_ ` _ \ / _` | '__| | | | # ___) | |_| | | | | | | | | | | | (_| | | | |_| | # |____/ \__,_|_| |_| |_|_| |_| |_|\__,_|_| \__, | # |___/ message(STATUS "Build options") get_cmake_property(all_variables VARIABLES) string(REGEX MATCHALL "(^|;)LINK_[A-Z_]+" link_variables "${all_variables}") foreach(variable ${link_variables}) message(" ${variable}: ${${variable}}") endforeach() message(STATUS "Build configuration") if(CMAKE_BUILD_TYPE) message(" Build type: ${CMAKE_BUILD_TYPE}") else() message(" Build type: Set by IDE") endif() link-Link-1.0.0/.travis.yml0000644000175000017500000001053512765602651015721 0ustar zmoelnigzmoelnig# Copyright (c) 2016 Ableton. All Rights Reserved. language: cpp sudo: required dist: trusty branches: only: - master matrix: include: ########################################################################### # Build with the main configuration on all the supported compilers ########################################################################### # Mac OS X / XCode 7.1, 64-bit Debug - os: osx env: WORDSIZE=64 CONFIGURATION=Debug osx_image: xcode7.1 compiler: clang # Mac OS X / XCode 7.1, 64-bit Release - os: osx env: WORDSIZE=64 CONFIGURATION=Release osx_image: xcode7.1 compiler: clang # Linux with Clang 3.6, 64-bit Debug - os: linux compiler: clang addons: apt: sources: ['ubuntu-toolchain-r-test'] packages: ['clang-3.6', 'g++-5', 'valgrind', 'p7zip-full', 'portaudio19-dev', 'cmake', 'cmake-data'] env: COMPILER=clang++-3.6 WORDSIZE=64 CONFIGURATION=Debug # Linux with Clang 3.6, 64-bit Release - os: linux compiler: clang addons: apt: sources: ['ubuntu-toolchain-r-test'] packages: ['clang-3.6', 'g++-5', 'valgrind', 'p7zip-full', 'portaudio19-dev', 'cmake', 'cmake-data'] env: COMPILER=clang++-3.6 WORDSIZE=64 CONFIGURATION=Release # Linux with GCC 5.x, 32-bit Release # - os: linux # compiler: gcc # addons: # apt: # sources: ['ubuntu-toolchain-r-test'] # packages: ['g++-5', 'g++-5-multilib', 'linux-libc-dev:i386', 'valgrind:i386', # 'p7zip-full', 'libxext-dev:i386', 'libglapi-mesa:i386', # 'libgl1-mesa-glx:i386', 'libgl1-mesa-dev:i386', # 'portaudio19-dev:i386', 'libglib2.0-0:i386', 'cmake', 'cmake-data'] # env: COMPILER=g++-5 WORDSIZE=32 CONFIGURATION=Release # Linux with GCC 5.x, 64-bit Release - os: linux compiler: gcc addons: apt: sources: ['ubuntu-toolchain-r-test', 'george-edison55-precise-backports'] packages: ['g++-5', 'valgrind', 'p7zip-full', 'portaudio19-dev', 'cmake', 'cmake-data'] env: COMPILER=g++-5 WORDSIZE=64 CONFIGURATION=Release # Code formatting verification - os: linux compiler: clang env: CONFIGURATION=Formatting LLVM_VERSION=3.8.0 before_install: # Do indentation check - | if [ "$CONFIGURATION" = "Formatting" ]; then wget -O - http://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - echo deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-3.8 main | sudo tee --append /etc/apt/sources.list sudo apt-get update && sudo apt-get -y install clang-format-3.8 python ci/check-formatting.py -c $(which clang-format-3.8) exit $? fi # Override Travis' CXX Flag - CXX=$COMPILER # Install homebrew packages for Mac OS X - if [ "$TRAVIS_OS_NAME" = "osx" ]; then brew update && brew install cmake ninja qt5; fi # Install QT for Linux manually, since the QT packages are not whitelisted by Travis - if [ "$TRAVIS_OS_NAME" = "linux" ]; then ./ci/install-qt-5.sh $WORDSIZE; fi install: - git submodule update --init --recursive script: - | set -e if [ "$TRAVIS_OS_NAME" = "osx" ]; then PATH=`brew --prefix qt5`/bin:${PATH} python ci/configure.py --configuration $CONFIGURATION --generator Ninja --with-qt python ci/build.py --configuration $CONFIGURATION --arguments "all -v" else if [ "$WORDSIZE" -eq 64 ]; then PATH=$PWD/5.5/gcc_64:${PATH} python ci/configure.py --configuration $CONFIGURATION --wordsize $WORDSIZE --with-qt else PATH=$PWD/5.5/gcc:${PATH} python ci/configure.py --configuration $CONFIGURATION --wordsize $WORDSIZE --with-qt fi python ci/build.py --configuration $CONFIGURATION --arguments "VERBOSE=1 -j8" fi # Build Tests and run with Valgrind (Linux 64-bit only). Mac OSX supports # valgrind via homebrew, but there is no bottle formula, so it must be # compiled by brew and this takes way too much time on the build server. - | set -e if [ "$TRAVIS_OS_NAME" = "linux" ]; then python ci/run-tests.py --target LinkCoreTest --valgrind python ci/run-tests.py --target LinkDiscoveryTest --valgrind else python ci/run-tests.py --target LinkCoreTest python ci/run-tests.py --target LinkDiscoveryTest fi link-Link-1.0.0/.clang-format0000644000175000017500000000260012765602651016155 0ustar zmoelnigzmoelnigLanguage: Cpp BasedOnStyle: LLVM AccessModifierOffset: -2 AlignAfterOpenBracket: false AlignEscapedNewlinesLeft: false AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: true BinPackParameters: false BreakBeforeBinaryOperators: NonAssignment BreakBeforeBraces: Allman BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: true ColumnLimit: 90 ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 2 ContinuationIndentWidth: 2 Cpp11BracedListStyle: true DerivePointerAlignment: false DerivePointerBinding: false IndentCaseLabels: false IndentFunctionDeclarationAfterType: false IndentWidth: 2 KeepEmptyLinesAtTheStartOfBlocks: true MaxEmptyLinesToKeep: 2 NamespaceIndentation: None PenaltyBreakBeforeFirstCallParameter: 0 PenaltyReturnTypeOnItsOwnLine: 1000 PointerAlignment: Left PointerBindsToType: true SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInCStyleCastParentheses: false SpacesInParentheses: false Standard: C++11 UseTab: Never link-Link-1.0.0/include/0000755000175000017500000000000012765602651015227 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/CMakeLists.txt0000644000175000017500000001122012765602651017763 0ustar zmoelnigzmoelnigcmake_minimum_required(VERSION 3.0) project(LinkCore) # ____ # / ___|___ _ __ ___ # | | / _ \| '__/ _ \ # | |__| (_) | | | __/ # \____\___/|_| \___| # set(link_core_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ableton/link) set(link_core_HEADERS ${link_core_DIR}/Beats.hpp ${link_core_DIR}/ClientSessionTimelines.hpp ${link_core_DIR}/Controller.hpp ${link_core_DIR}/Gateway.hpp ${link_core_DIR}/GhostXForm.hpp ${link_core_DIR}/HostTimeFilter.hpp ${link_core_DIR}/Kalman.hpp ${link_core_DIR}/LinearRegression.hpp ${link_core_DIR}/Measurement.hpp ${link_core_DIR}/MeasurementEndpointV4.hpp ${link_core_DIR}/MeasurementService.hpp ${link_core_DIR}/NodeId.hpp ${link_core_DIR}/NodeState.hpp ${link_core_DIR}/PayloadEntries.hpp ${link_core_DIR}/Peers.hpp ${link_core_DIR}/PeerState.hpp ${link_core_DIR}/Phase.hpp ${link_core_DIR}/PingResponder.hpp ${link_core_DIR}/SessionId.hpp ${link_core_DIR}/Sessions.hpp ${link_core_DIR}/Tempo.hpp ${link_core_DIR}/Timeline.hpp ${link_core_DIR}/v1/Messages.hpp PARENT_SCOPE ) # ____ _ # | _ \(_)___ ___ _____ _____ _ __ _ _ # | | | | / __|/ __/ _ \ \ / / _ \ '__| | | | # | |_| | \__ \ (_| (_) \ V / __/ | | |_| | # |____/|_|___/\___\___/ \_/ \___|_| \__, | # |___/ set(link_discovery_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ableton/discovery) set(link_discovery_HEADERS ${link_discovery_DIR}/InterfaceScanner.hpp ${link_discovery_DIR}/IpV4Interface.hpp ${link_discovery_DIR}/MessageTypes.hpp ${link_discovery_DIR}/NetworkByteStreamSerializable.hpp ${link_discovery_DIR}/Payload.hpp ${link_discovery_DIR}/PeerGateway.hpp ${link_discovery_DIR}/PeerGateways.hpp ${link_discovery_DIR}/Service.hpp ${link_discovery_DIR}/Socket.hpp ${link_discovery_DIR}/UdpMessenger.hpp ${link_discovery_DIR}/v1/Messages.hpp PARENT_SCOPE ) # ____ _ _ __ # | _ \| | __ _| |_ / _| ___ _ __ _ __ ___ # | |_) | |/ _` | __| |_ / _ \| '__| '_ ` _ \ # | __/| | (_| | |_| _| (_) | | | | | | | | # |_| |_|\__,_|\__|_| \___/|_| |_| |_| |_| # set(link_platform_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ableton/platforms) set(link_platform_HEADERS ${link_platform_DIR}/Config.hpp ${link_platform_DIR}/asio/AsioService.hpp ${link_platform_DIR}/asio/AsioTimer.hpp ${link_platform_DIR}/asio/AsioWrapper.hpp ${link_platform_DIR}/asio/Context.hpp ${link_platform_DIR}/asio/PooledHandlerContext.hpp ${link_platform_DIR}/asio/Socket.hpp ${link_platform_DIR}/asio/Util.hpp ) if(UNIX) set(link_platform_HEADERS ${link_platform_HEADERS} ${link_platform_DIR}/posix/ScanIpIfAddrs.hpp ) if(APPLE) set(link_platform_HEADERS ${link_platform_HEADERS} ${link_platform_DIR}/darwin/Clock.hpp ${link_platform_DIR}/darwin/Darwin.hpp ) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") set(link_platform_HEADERS ${link_platform_HEADERS} ${link_platform_DIR}/linux/Linux.hpp ${link_platform_DIR}/stl/Clock.hpp ) endif() elseif(WIN32) set(link_platform_HEADERS ${link_platform_HEADERS} ${link_platform_DIR}/windows/Clock.hpp ${link_platform_DIR}/windows/ScanIpIfAddrs.hpp ) endif() set(link_platform_HEADERS ${link_platform_HEADERS} PARENT_SCOPE ) # _ _ _ _ _ # | | | | |_(_) | # | | | | __| | | # | |_| | |_| | | # \___/ \__|_|_| # set(link_util_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ableton/util) set(link_util_HEADERS ${link_util_DIR}/Injected.hpp ${link_util_DIR}/Log.hpp ${link_util_DIR}/SafeAsyncHandler.hpp ${link_util_DIR}/SampleTiming.hpp PARENT_SCOPE ) # _____ _ _ # | ____|_ ___ __ ___ _ __| |_ ___ __| | # | _| \ \/ / '_ \ / _ \| '__| __/ _ \/ _` | # | |___ > <| |_) | (_) | | | || __/ (_| | # |_____/_/\_\ .__/ \___/|_| \__\___|\__,_| # |_| # This list contains all of the headers needed by most Link projects. # Usually, just adding this variable to your linker targets will place # all relevant Link headers in your project. set(link_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ableton) set(link_HEADERS ${link_core_HEADERS} ${link_discovery_HEADERS} ${link_platform_HEADERS} ${link_util_HEADERS} ${link_DIR}/Link.hpp ${link_DIR}/Link.ipp PARENT_SCOPE ) set(link_test_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ableton/test) set(link_test_HEADERS ${link_discovery_DIR}/test/Interface.hpp ${link_discovery_DIR}/test/PayloadEntries.hpp ${link_discovery_DIR}/test/Socket.hpp ${link_util_DIR}/test/IoService.hpp ${link_util_DIR}/test/Timer.hpp ${link_test_DIR}/CatchWrapper.hpp ${link_test_DIR}/serial_io/Context.hpp ${link_test_DIR}/serial_io/Fixture.hpp ${link_test_DIR}/serial_io/SchedulerTree.hpp ${link_test_DIR}/serial_io/Timer.hpp PARENT_SCOPE ) link-Link-1.0.0/include/ableton/0000755000175000017500000000000012765602651016653 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/Link.hpp0000644000175000017500000002716512765602651020274 0ustar zmoelnigzmoelnig/*! @file Link.hpp * @copyright 2016, Ableton AG, Berlin. All rights reserved. * @brief Library for cross-device shared tempo and quantized beat grid * * @license: * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { /*! @class Link * @brief Class that represents a participant in a Link session. * * @discussion Each Link instance has its own beat timeline that * starts running from beat 0 at the initial tempo when * constructed. A Link instance is initially disabled after * construction, which means that it will not communicate on the * network. Once enabled, a Link instance initiates network * communication in an effort to discover other peers. When peers are * discovered, they immediately become part of a shared Link session. * * Each method of the Link type documents its thread-safety and * realtime-safety properties. When a method is marked thread-safe, * it means it is safe to call from multiple threads * concurrently. When a method is marked realtime-safe, it means that * it does not block and is appropriate for use in the thread that * performs audio IO. * * Link provides one Timeline capture/commit method pair for use in the * audio thread and one for all other application contexts. In * general, modifying the Link timeline should be done in the audio * thread for the most accurate timing results. The ability to modify * the Link timeline from application threads should only be used in * cases where an application's audio thread is not actively running * or if it doesn't generate audio at all. Modifying the Link * timeline from both the audio thread and an application thread * concurrently is not advised and will potentially lead to * unexpected behavior. */ class Link { public: using Clock = link::platform::Clock; class Timeline; /*! @brief Construct with an initial tempo. */ Link(double bpm); /*! @brief Link instances cannot be copied or moved */ Link(const Link&) = delete; Link& operator=(const Link&) = delete; Link(Link&&) = delete; Link& operator=(Link&&) = delete; /*! @brief Is Link currently enabled? * Thread-safe: yes * Realtime-safe: yes */ bool isEnabled() const; /*! @brief Enable/disable Link. * Thread-safe: yes * Realtime-safe: no */ void enable(bool bEnable); /*! @brief How many peers are currently connected in a Link session? * Thread-safe: yes * Realtime-safe: yes */ std::size_t numPeers() const; /*! @brief Register a callback to be notified when the number of * peers in the Link session changes. * Thread-safe: yes * Realtime-safe: no * * @discussion The callback is invoked on a Link-managed thread. * * @param callback The callback signature is: * void (std::size_t numPeers) */ template void setNumPeersCallback(Callback callback); /*! @brief Register a callback to be notified when the session * tempo changes. * Thread-safe: yes * Realtime-safe: no * * @discussion The callback is invoked on a Link-managed thread. * * @param callback The callback signature is: void (double bpm) */ template void setTempoCallback(Callback callback); /*! @brief The clock used by Link. * Thread-safe: yes * Realtime-safe: yes * * @discussion The Clock type is a platform-dependent * representation of the system clock. It exposes a ticks() method * that returns the current ticks of the system clock as well as * micros(), which is a normalized representation of the current system * time in std::chrono::microseconds. It also provides conversion * functions ticksToMicros() and microsToTicks() to faciliate * converting between these units. */ Clock clock() const; /*! @brief Capture the current Link timeline from the audio thread. * Thread-safe: no * Realtime-safe: yes * * @discussion This method should ONLY be called in the audio thread * and must not be accessed from any other threads. The returned * Timeline stores a snapshot of the current Link state, so it * should be captured and used in a local scope. Storing the * Timeline for later use in a different context is not advised * because it will provide an outdated view on the Link state. */ Timeline captureAudioTimeline() const; /*! @brief Commit the given timeline to the Link session from the * audio thread. * Thread-safe: no * Realtime-safe: yes * * @discussion This method should ONLY be called in the audio * thread. The given timeline will replace the current Link * timeline. Modifications to the session based on the new timeline * will be communicated to other peers in the session. */ void commitAudioTimeline(Timeline timeline); /*! @brief Capture the current Link timeline from an application * thread. * Thread-safe: yes * Realtime-safe: no * * @discussion Provides a mechanism for capturing the Link timeline * from an application thread (other than the audio thread). The * returned Timeline stores a snapshot of the current Link state, * so it should be captured and used in a local scope. Storing the * Timeline for later use in a different context is not advised * because it will provide an outdated view on the Link state. */ Timeline captureAppTimeline() const; /*! @brief Commit the given timeline to the Link session from an * application thread. * Thread-safe: yes * Realtime-safe: no * * @discussion The given timeline will replace the current Link * timeline. Modifications to the session based on the new timeline * will be communicated to other peers in the session. */ void commitAppTimeline(Timeline timeline); /*! @class Timeline * @brief Representation of a mapping between time and beats for * varying quanta. * * @discussion A Timeline object is intended for use in a local * scope within a single thread - none of its methods are * thread-safe. All of its methods are non-blocking, so it is safe * to use from a realtime thread. */ class Timeline { public: Timeline(const link::Timeline timeline, const bool bRespectQuantum); /*! @brief: The tempo of the timeline, in bpm */ double tempo() const; /*! @brief: Set the timeline tempo to the given bpm value, taking * effect at the given time. */ void setTempo(double bpm, std::chrono::microseconds atTime); /*! @brief: Get the beat value corresponding to the given time * for the given quantum. * * @discussion: The magnitude of the resulting beat value is * unique to this Link instance, but its phase with respect to * the provided quantum is shared among all session * peers. For non-negative beat values, the following * property holds: fmod(beatAtTime(t, q), q) == phaseAtTime(t, q) */ double beatAtTime(std::chrono::microseconds time, double quantum) const; /*! @brief: Get the session phase at the given time for the given * quantum. * * @discussion: The result is in the interval [0, quantum). The * result is equivalent to fmod(beatAtTime(t, q), q) for * non-negative beat values. This method is convenient if the * client is only interested in the phase and not the beat * magnitude. Also, unlike fmod, it handles negative beat values * correctly. */ double phaseAtTime(std::chrono::microseconds time, double quantum) const; /*! @brief: Get the time at which the given beat occurs for the * given quantum. * * @discussion: The inverse of beatAtTime, assuming a constant * tempo. beatAtTime(timeAtBeat(b, q), q) === b. */ std::chrono::microseconds timeAtBeat(double beat, double quantum) const; /*! @brief: Attempt to map the given beat to the given time in the * context of the given quantum. * * @discussion: This method behaves differently depending on the * state of the session. If no other peers are connected, * then this instance is in a session by itself and is free to * re-map the beat/time relationship whenever it pleases. In this * case, beatAtTime(time, quantum) == beat after this method has * been called. * * If there are other peers in the session, this instance * should not abruptly re-map the beat/time relationship in the * session because that would lead to beat discontinuities among * the other peers. In this case, the given beat will be mapped * to the next time value greater than the given time with the * same phase as the given beat. * * This method is specifically designed to enable the concept of * "quantized launch" in client applications. If there are no other * peers in the session, then an event (such as starting * transport) happens immediately when it is requested. If there * are other peers, however, we wait until the next time at which * the session phase matches the phase of the event, thereby * executing the event in-phase with the other peers in the * session. The client only needs to invoke this method to * achieve this behavior and should not need to explicitly check * the number of peers. */ void requestBeatAtTime(double beat, std::chrono::microseconds time, double quantum); /*! @brief: Rudely re-map the beat/time relationship for all peers * in a session. * * @discussion: DANGER: This method should only be needed in * certain special circumstances. Most applications should not * use it. It is very similar to requestBeatAtTime except that it * does not fall back to the quantizing behavior when it is in a * session with other peers. Calling this method will * unconditionally map the given beat to the given time and * broadcast the result to the session. This is very anti-social * behavior and should be avoided. * * One of the few legitimate uses of this method is to * synchronize a Link session with an external clock source. By * periodically forcing the beat/time mapping according to an * external clock source, a peer can effectively bridge that * clock into a Link session. Much care must be taken at the * application layer when implementing such a feature so that * users do not accidentally disrupt Link sessions that they may * join. */ void forceBeatAtTime(double beat, std::chrono::microseconds time, double quantum); private: friend Link; link::Timeline mOriginalTimeline; bool mbRespectQuantum; link::Timeline mTimeline; }; private: std::mutex mCallbackMutex; link::PeerCountCallback mPeerCountCallback; link::TempoCallback mTempoCallback; Clock mClock; link::platform::Controller mController; }; } // ableton #include link-Link-1.0.0/include/ableton/platforms/0000755000175000017500000000000012765602651020662 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/platforms/linux/0000755000175000017500000000000012765602651022021 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/platforms/linux/Linux.hpp0000644000175000017500000000174412765602651023637 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #ifndef ntohll #define ntohll(x) bswap_64(x) #endif #ifndef htonll #define htonll(x) bswap_64(x) #endif link-Link-1.0.0/include/ableton/platforms/asio/0000755000175000017500000000000012765602651021615 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/platforms/asio/AsioTimer.hpp0000644000175000017500000000701112765602651024221 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace platforms { namespace asio { // This implementation is based on the boost::asio::system_timer concept. // Since boost::system_timer doesn't support move semantics, we create a wrapper // with a unique_ptr to get a movable type. It also handles an inconvenient // aspect of asio timers, which is that you must explicitly guard against the // handler firing after cancellation. We handle this by use of the SafeAsyncHandler // utility. AsioTimer therefore guarantees that a handler will not be called after // the destruction of the timer, or after the timer has been canceled. class AsioTimer { public: using ErrorCode = ::asio::error_code; using TimePoint = std::chrono::system_clock::time_point; AsioTimer(::asio::io_service& io) : mpTimer(new ::asio::system_timer(io)) , mpAsyncHandler(std::make_shared()) { } ~AsioTimer() { // The timer may not be valid anymore if this instance was moved from if (mpTimer != nullptr) { // Ignore errors during cancellation cancel(); } } AsioTimer(const AsioTimer&) = delete; AsioTimer& operator=(const AsioTimer&) = delete; // Enable move construction but not move assignment. Move assignment // would get weird - would have to handle outstanding handlers AsioTimer(AsioTimer&& rhs) : mpTimer(std::move(rhs.mpTimer)) , mpAsyncHandler(std::move(rhs.mpAsyncHandler)) { } void expires_at(std::chrono::system_clock::time_point tp) { mpTimer->expires_at(std::move(tp)); } template void expires_from_now(T duration) { mpTimer->expires_from_now(std::move(duration)); } ErrorCode cancel() { ErrorCode ec; mpTimer->cancel(ec); mpAsyncHandler->mpHandler = nullptr; return ec; } template void async_wait(Handler handler) { *mpAsyncHandler = std::move(handler); mpTimer->async_wait(util::makeAsyncSafe(mpAsyncHandler)); } TimePoint now() const { return std::chrono::system_clock::now(); } private: struct AsyncHandler { template AsyncHandler& operator=(Handler handler) { mpHandler = [handler](ErrorCode ec) { handler(std::move(ec)); }; return *this; } void operator()(ErrorCode ec) { if (mpHandler) { mpHandler(std::move(ec)); } } std::function mpHandler; }; std::unique_ptr<::asio::system_timer> mpTimer; std::shared_ptr mpAsyncHandler; }; } // namespace asio } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/asio/AsioService.hpp0000644000175000017500000000500712765602651024544 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace platforms { namespace asio { class AsioService { public: using Timer = AsioTimer; AsioService() : AsioService(DefaultHandler{}) { } template explicit AsioService(ExceptionHandler exceptHandler) : mpWork(new ::asio::io_service::work(mService)) { mThread = std::thread{[](::asio::io_service& service, ExceptionHandler handler) { for (;;) { try { service.run(); break; } catch (const typename ExceptionHandler::Exception& exception) { handler(exception); } } }, std::ref(mService), std::move(exceptHandler)}; } ~AsioService() { mpWork.reset(); mThread.join(); } AsioTimer makeTimer() { return {mService}; } template void post(Handler handler) { mService.post(std::move(handler)); } ::asio::io_service mService; private: // Default handler is hidden and defines a hidden exception type // that will never be thrown by other code, so it effectively does // not catch. struct DefaultHandler { struct Exception { }; void operator()(const Exception&) { } }; std::unique_ptr<::asio::io_service::work> mpWork; std::thread mThread; }; } // namespace asio } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/asio/AsioWrapper.hpp0000644000175000017500000000410412765602651024561 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once /*! * \brief Wrapper file for AsioStandalone library * * This file includes all necessary headers from the AsioStandalone library which are used * by Link. */ #pragma push_macro("ASIO_STANDALONE") #define ASIO_STANDALONE 1 #pragma push_macro("ASIO_NO_TYPEID") #define ASIO_NO_TYPEID 1 #if LINK_PLATFORM_WINDOWS #pragma push_macro("INCL_EXTRA_HTON_FUNCTIONS") #define INCL_EXTRA_HTON_FUNCTIONS 1 #endif // Visual Studio: Disable Warnings #if defined(_MSC_VER) #pragma warning(push) // C4191: 'operator/operation': unsafe conversion from 'type of expression' to // 'type required' #pragma warning(disable : 4191) // C4548: expression before comma has no effect; expected expression with side-effect #pragma warning(disable : 4548) // C4619: #pragma warning : there is no warning number 'number' #pragma warning(disable : 4619) // C4675: 'function' : resolved overload was found by argument-dependent lookup #pragma warning(disable : 4675) #endif #include #include #if LINK_PLATFORM_WINDOWS #pragma pop_macro("INCL_EXTRA_HTON_FUNCTIONS") #endif #pragma pop_macro("ASIO_STANDALONE") #pragma pop_macro("ASIO_NO_TYPEID") // Visual Studio: Disable Warnings #if defined(_MSC_VER) #pragma warning(pop) #endif link-Link-1.0.0/include/ableton/platforms/asio/Context.hpp0000644000175000017500000001154212765602651023755 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include namespace ableton { namespace platforms { namespace asio { template class Context { public: using Timer = AsioTimer; using Log = LogT; template using Socket = asio::Socket; template using RealTimeContext = PooledHandlerContext; Context() : Context(DefaultHandler{}) { } template explicit Context(ExceptionHandler exceptHandler) : mpService(new ::asio::io_service()) , mpWork(new ::asio::io_service::work(*mpService)) { mThread = std::thread{[](::asio::io_service& service, ExceptionHandler handler) { for (;;) { try { service.run(); break; } catch (const typename ExceptionHandler::Exception& exception) { handler(exception); } } }, std::ref(*mpService), std::move(exceptHandler)}; } Context(const Context&) = delete; Context(Context&& rhs) : mpService(std::move(rhs.mpService)) , mpWork(std::move(rhs.mpWork)) , mThread(std::move(rhs.mThread)) , mLog(std::move(rhs.mLog)) , mScanIpIfAddrs(std::move(rhs.mScanIpIfAddrs)) { } ~Context() { if (mpService) { mpWork.reset(); mThread.join(); } } template Socket openUnicastSocket(const ::asio::ip::address_v4& addr) { auto socket = Socket{*mpService}; socket.mpImpl->mSocket.set_option( ::asio::ip::multicast::enable_loopback(addr.is_loopback())); socket.mpImpl->mSocket.set_option(::asio::ip::multicast::outbound_interface(addr)); socket.mpImpl->mSocket.bind(::asio::ip::udp::endpoint{addr, 0}); return socket; } template Socket openMulticastSocket(const ::asio::ip::address_v4& addr) { auto socket = Socket{*mpService}; socket.mpImpl->mSocket.set_option(::asio::ip::udp::socket::reuse_address(true)); socket.mpImpl->mSocket.set_option( ::asio::socket_base::broadcast(!addr.is_loopback())); socket.mpImpl->mSocket.set_option( ::asio::ip::multicast::enable_loopback(addr.is_loopback())); socket.mpImpl->mSocket.set_option(::asio::ip::multicast::outbound_interface(addr)); socket.mpImpl->mSocket.bind({::asio::ip::address::from_string("0.0.0.0"), discovery::multicastEndpoint().port()}); socket.mpImpl->mSocket.set_option(::asio::ip::multicast::join_group( discovery::multicastEndpoint().address().to_v4(), addr)); return socket; } std::vector<::asio::ip::address> scanNetworkInterfaces() { return mScanIpIfAddrs(); } Timer makeTimer() const { return {*mpService}; } Log& log() { return mLog; } template void async(Handler handler) { mpService->post(std::move(handler)); } Context clone() const { return {}; } template Context clone(ExceptionHandler handler) const { return Context{std::move(handler)}; } private: // Default handler is hidden and defines a hidden exception type // that will never be thrown by other code, so it effectively does // not catch. struct DefaultHandler { struct Exception { }; void operator()(const Exception&) { } }; std::unique_ptr<::asio::io_service> mpService; std::unique_ptr<::asio::io_service::work> mpWork; std::thread mThread; Log mLog; ScanIpIfAddrs mScanIpIfAddrs; }; } // namespace asio } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/asio/PooledHandlerContext.hpp0000644000175000017500000000610612765602651026416 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace platforms { namespace asio { template struct PooledHandlerContext { PooledHandlerContext(util::Injected io) : mIo(std::move(io)) { // initialize the handler free store mFreeStack.reserve(MaxNumHandlers); for (std::size_t i = 0; i < MaxNumHandlers; ++i) { mFreeStack.push_back(reinterpret_cast(mRaw + i)); } } template void async(Handler handler) { try { mIo->async(HandlerWrapper{*this, std::move(handler)}); } catch (std::bad_alloc) { warning(mIo->log()) << "Handler dropped due to low memory pool"; } } template struct HandlerWrapper { HandlerWrapper(PooledHandlerContext& context, Handler handler) : mContext(context) , mHandler(std::move(handler)) { } void operator()() { mHandler(); } // Use pooled allocation so that posting handlers will not cause // system allocation friend void* asio_handler_allocate( const std::size_t size, HandlerWrapper* const pHandler) { if (size > MaxHandlerSize || pHandler->mContext.mFreeStack.empty()) { // Going over the max handler size is a programming error, as // this is not a dynamically variable value. assert(size <= MaxHandlerSize); throw std::bad_alloc(); } else { const auto p = pHandler->mContext.mFreeStack.back(); pHandler->mContext.mFreeStack.pop_back(); return p; } } friend void asio_handler_deallocate( void* const p, std::size_t, HandlerWrapper* const pHandler) { pHandler->mContext.mFreeStack.push_back(p); } PooledHandlerContext& mContext; Handler mHandler; }; using MemChunk = typename std::aligned_storage::value>::type; MemChunk mRaw[MaxNumHandlers]; std::vector mFreeStack; util::Injected mIo; }; } // namespace asio } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/asio/Socket.hpp0000644000175000017500000000574712765602651023573 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include namespace ableton { namespace platforms { namespace asio { template struct Socket { Socket(::asio::io_service& io) : mpImpl(std::make_shared(io)) { } Socket(const Socket&) = delete; Socket& operator=(const Socket&) = delete; Socket(Socket&& rhs) : mpImpl(std::move(rhs.mpImpl)) { } std::size_t send(const uint8_t* const pData, const size_t numBytes, const ::asio::ip::udp::endpoint& to) { assert(numBytes < MaxPacketSize); return mpImpl->mSocket.send_to(::asio::buffer(pData, numBytes), to); } template void receive(Handler handler) { mpImpl->mHandler = std::move(handler); mpImpl->mSocket.async_receive_from( ::asio::buffer(mpImpl->mReceiveBuffer, MaxPacketSize), mpImpl->mSenderEndpoint, util::makeAsyncSafe(mpImpl)); } ::asio::ip::udp::endpoint endpoint() const { return mpImpl->mSocket.local_endpoint(); } struct Impl { Impl(::asio::io_service& io) : mSocket(io, ::asio::ip::udp::v4()) { } ~Impl() { // Ignore error codes in shutdown and close as the socket may // have already been forcibly closed ::asio::error_code ec; mSocket.shutdown(::asio::ip::udp::socket::shutdown_both, ec); mSocket.close(ec); } void operator()(const ::asio::error_code& error, const std::size_t numBytes) { if (!error && numBytes > 0 && numBytes <= MaxPacketSize) { const auto bufBegin = begin(mReceiveBuffer); mHandler(mSenderEndpoint, bufBegin, bufBegin + static_cast(numBytes)); } } ::asio::ip::udp::socket mSocket; ::asio::ip::udp::endpoint mSenderEndpoint; using Buffer = std::array; Buffer mReceiveBuffer; using ByteIt = typename Buffer::const_iterator; std::function mHandler; }; std::shared_ptr mpImpl; }; } // namespace asio } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/asio/Util.hpp0000644000175000017500000000242212765602651023243 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace platforms { namespace asio { // Utility for making v4 or v6 ip addresses from raw bytes in network byte-order template AsioAddrType makeAddress(const char* pAddr) { using namespace std; typename AsioAddrType::bytes_type bytes; copy(pAddr, pAddr + bytes.size(), begin(bytes)); return AsioAddrType{bytes}; } } // asio } // platforms } // ableton link-Link-1.0.0/include/ableton/platforms/Config.hpp0000644000175000017500000000412512765602651022602 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #if LINK_PLATFORM_WINDOWS #include #include #include #elif LINK_PLATFORM_MACOSX #include #include #include #elif LINK_PLATFORM_LINUX #include #include #include #endif namespace ableton { namespace link { namespace platform { #if LINK_PLATFORM_WINDOWS using Clock = platforms::windows::Clock; using IoContext = platforms::asio::Context; #elif LINK_PLATFORM_MACOSX using Clock = platforms::darwin::Clock; using IoContext = platforms::asio::Context; #elif LINK_PLATFORM_LINUX using Clock = platforms::stl::Clock; using IoContext = platforms::asio::Context; #endif using Controller = Controller; } // platform } // link } // ableton link-Link-1.0.0/include/ableton/platforms/darwin/0000755000175000017500000000000012765602651022146 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/platforms/darwin/Darwin.hpp0000644000175000017500000000210112765602651024075 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once // ntohll and htonll are not defined in 10.7 SDK, so we provide a compatibility macro here #ifndef ntohll #define ntohll(x) __DARWIN_OSSwapInt64(x) #endif #ifndef htonll #define htonll(x) __DARWIN_OSSwapInt64(x) #endif link-Link-1.0.0/include/ableton/platforms/darwin/Clock.hpp0000644000175000017500000000335512765602651023720 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace platforms { namespace darwin { struct Clock { using Ticks = std::uint64_t; using Micros = std::chrono::microseconds; Clock() { mach_timebase_info_data_t timeInfo; mach_timebase_info(&timeInfo); // numer / denom gives nanoseconds, we want microseconds mTicksToMicros = timeInfo.numer / (timeInfo.denom * 1000.); } Micros ticksToMicros(const Ticks ticks) const { return Micros{std::llround(mTicksToMicros * ticks)}; } Ticks microsToTicks(const Micros micros) const { return static_cast(micros.count() / mTicksToMicros); } Ticks ticks() const { return mach_absolute_time(); } std::chrono::microseconds micros() const { return ticksToMicros(ticks()); } double mTicksToMicros; }; } // namespace darwin } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/posix/0000755000175000017500000000000012765602651022024 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/platforms/posix/ScanIpIfAddrs.hpp0000644000175000017500000000570212765602651025153 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include namespace ableton { namespace platforms { namespace posix { namespace detail { // RAII type to make [get,free]ifaddrs function pairs exception safe class GetIfAddrs { public: GetIfAddrs() { if (getifaddrs(&interfaces)) // returns 0 on success { interfaces = NULL; } } ~GetIfAddrs() { if (interfaces) freeifaddrs(interfaces); } // RAII must not copy GetIfAddrs(GetIfAddrs&) = delete; GetIfAddrs& operator=(GetIfAddrs&) = delete; template void withIfAddrs(Function f) { if (interfaces) f(*interfaces); } private: struct ifaddrs* interfaces = NULL; }; } // detail // Posix implementation of ip interface address scanner struct ScanIpIfAddrs { // Scan active network interfaces and return corresponding addresses // for all ip-based interfaces. std::vector<::asio::ip::address> operator()() { std::vector<::asio::ip::address> addrs; detail::GetIfAddrs getIfAddrs; getIfAddrs.withIfAddrs([&addrs](const struct ifaddrs& interfaces) { const struct ifaddrs* interface; for (interface = &interfaces; interface; interface = interface->ifa_next) { auto addr = reinterpret_cast(interface->ifa_addr); if (addr && interface->ifa_flags & IFF_UP) { if (addr->sin_family == AF_INET) { auto bytes = reinterpret_cast(&addr->sin_addr); addrs.emplace_back(asio::makeAddress<::asio::ip::address_v4>(bytes)); } else if (addr->sin_family == AF_INET6) { auto addr6 = reinterpret_cast(addr); auto bytes = reinterpret_cast(&addr6->sin6_addr); addrs.emplace_back(asio::makeAddress<::asio::ip::address_v6>(bytes)); } } } }); return addrs; } }; } // namespace posix } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/windows/0000755000175000017500000000000012765602651022354 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/platforms/windows/ScanIpIfAddrs.hpp0000644000175000017500000001003312765602651025474 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include #include #pragma comment(lib, "iphlpapi.lib") #pragma comment(lib, "ws2_32.lib") namespace ableton { namespace platforms { namespace windows { namespace detail { // RAII type to make [get,free]ifaddrs function pairs exception safe class GetIfAddrs { public: GetIfAddrs() { const int MAX_TRIES = 3; // MSFT recommendation const int WORKING_BUFFER_SIZE = 15000; // MSFT recommendation DWORD adapter_addrs_buffer_size = WORKING_BUFFER_SIZE; for (int i = 0; i < MAX_TRIES; i++) { adapter_addrs = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addrs_buffer_size); assert(adapter_addrs); DWORD error = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, adapter_addrs, &adapter_addrs_buffer_size); if (error == ERROR_SUCCESS) { break; } // if buffer too small, use new buffer size in next iteration if (error == ERROR_BUFFER_OVERFLOW) { free(adapter_addrs); adapter_addrs = NULL; continue; } } } ~GetIfAddrs() { if (adapter_addrs) free(adapter_addrs); } // RAII must not copy GetIfAddrs(GetIfAddrs&) = delete; GetIfAddrs& operator=(GetIfAddrs&) = delete; template void withIfAddrs(Function f) { if (adapter_addrs) f(*adapter_addrs); } private: IP_ADAPTER_ADDRESSES* adapter_addrs; IP_ADAPTER_ADDRESSES* adapter; }; } // detail struct ScanIpIfAddrs { // Scan active network interfaces and return corresponding addresses // for all ip-based interfaces. std::vector<::asio::ip::address> operator()() { std::vector<::asio::ip::address> addrs; detail::GetIfAddrs getIfAddrs; getIfAddrs.withIfAddrs([&addrs](const IP_ADAPTER_ADDRESSES& interfaces) { const IP_ADAPTER_ADDRESSES* networkInterface; for (networkInterface = &interfaces; networkInterface; networkInterface = networkInterface->Next) { for (IP_ADAPTER_UNICAST_ADDRESS* address = networkInterface->FirstUnicastAddress; NULL != address; address = address->Next) { auto family = address->Address.lpSockaddr->sa_family; if (AF_INET == family) { // IPv4 SOCKADDR_IN* addr4 = reinterpret_cast(address->Address.lpSockaddr); auto bytes = reinterpret_cast(&addr4->sin_addr); addrs.emplace_back(asio::makeAddress<::asio::ip::address_v4>(bytes)); } else if (AF_INET6 == family) { SOCKADDR_IN6* addr6 = reinterpret_cast(address->Address.lpSockaddr); auto bytes = reinterpret_cast(&addr6->sin6_addr); addrs.emplace_back(asio::makeAddress<::asio::ip::address_v6>(bytes)); } } } }); return addrs; } }; } // namespace windows } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/windows/Clock.hpp0000644000175000017500000000331612765602651024123 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace platforms { namespace windows { struct Clock { using Ticks = std::int64_t; using Micros = std::chrono::microseconds; Clock() { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); mTicksToMicros = 1.0e6 / frequency.QuadPart; } Micros ticksToMicros(const Ticks ticks) const { return Micros{std::llround(mTicksToMicros * ticks)}; } Ticks microsToTicks(const Micros micros) const { return static_cast(micros.count() / mTicksToMicros); } Ticks ticks() const { LARGE_INTEGER count; QueryPerformanceCounter(&count); return count.QuadPart; } std::chrono::microseconds micros() const { return ticksToMicros(ticks()); } double mTicksToMicros; }; } // namespace windows } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/platforms/stl/0000755000175000017500000000000012765602651021464 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/platforms/stl/Clock.hpp0000644000175000017500000000253412765602651023234 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace platforms { namespace stl { struct Clock { using Ticks = std::uint64_t; Clock() { mStartTime = std::chrono::high_resolution_clock::now(); } std::chrono::microseconds micros() const { using namespace std::chrono; return duration_cast(high_resolution_clock::now() - mStartTime); } std::chrono::high_resolution_clock::time_point mStartTime; }; } // namespace stl } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/discovery/0000755000175000017500000000000012765602651020662 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/discovery/v1/0000755000175000017500000000000012765602651021210 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/discovery/v1/Messages.hpp0000644000175000017500000001277012765602651023477 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace discovery { namespace v1 { // The maximum size of a message, in bytes const std::size_t kMaxMessageSize = 512; // Utility typedef for an array of bytes of maximum message size using MessageBuffer = std::array; using MessageType = uint8_t; using SessionGroupId = uint16_t; const MessageType kInvalid = 0; const MessageType kAlive = 1; const MessageType kResponse = 2; const MessageType kByeBye = 3; template struct MessageHeader { MessageType messageType; uint8_t ttl; SessionGroupId groupId; NodeId ident; friend std::uint32_t sizeInByteStream(const MessageHeader& header) { return discovery::sizeInByteStream(header.messageType) + discovery::sizeInByteStream(header.ttl) + discovery::sizeInByteStream(header.groupId) + discovery::sizeInByteStream(header.ident); } template friend It toNetworkByteStream(const MessageHeader& header, It out) { return discovery::toNetworkByteStream( header.ident, discovery::toNetworkByteStream( header.groupId, discovery::toNetworkByteStream(header.ttl, discovery::toNetworkByteStream(header.messageType, std::move(out))))); } template static std::pair fromNetworkByteStream(It begin, const It end) { using namespace std; MessageHeader header; tie(header.messageType, begin) = Deserialize::fromNetworkByteStream(begin, end); tie(header.ttl, begin) = Deserialize::fromNetworkByteStream(begin, end); tie(header.groupId, begin) = Deserialize::fromNetworkByteStream(begin, end); tie(header.ident, begin) = Deserialize::fromNetworkByteStream(begin, end); return make_pair(move(header), move(begin)); } }; namespace detail { // Types that are only used in the sending/parsing of messages, not // publicly exposed. using ProtocolHeader = std::array; const ProtocolHeader kProtocolHeader = {{'_', 'a', 's', 'd', 'p', '_', 'v', 1}}; // Must have at least kMaxMessageSize bytes available in the output stream template It encodeMessage(NodeId from, const uint8_t ttl, const MessageType messageType, const Payload& payload, It out) { using namespace std; const MessageHeader header = {messageType, ttl, 0, std::move(from)}; const auto messageSize = kProtocolHeader.size() + sizeInByteStream(header) + sizeInByteStream(payload); if (messageSize < kMaxMessageSize) { return toNetworkByteStream( payload, toNetworkByteStream( header, copy(begin(kProtocolHeader), end(kProtocolHeader), move(out)))); } else { throw range_error("Exceeded maximum message size"); } } } // namespace detail template It aliveMessage(NodeId from, const uint8_t ttl, const Payload& payload, It out) { return detail::encodeMessage(std::move(from), ttl, kAlive, payload, std::move(out)); } template It responseMessage(NodeId from, const uint8_t ttl, const Payload& payload, It out) { return detail::encodeMessage(std::move(from), ttl, kResponse, payload, std::move(out)); } template It byeByeMessage(NodeId from, It out) { return detail::encodeMessage( std::move(from), 0, kByeBye, makePayload(), std::move(out)); } template std::pair, It> parseMessageHeader(It bytesBegin, const It bytesEnd) { using namespace std; using ItDiff = typename iterator_traits::difference_type; MessageHeader header = {}; const auto protocolHeaderSize = discovery::sizeInByteStream(detail::kProtocolHeader); const auto minMessageSize = static_cast(protocolHeaderSize + sizeInByteStream(header)); // If there are enough bytes in the stream to make a header and if // the first bytes in the stream are the protocol header, then // proceed to parse the stream. if (distance(bytesBegin, bytesEnd) >= minMessageSize && equal(begin(detail::kProtocolHeader), end(detail::kProtocolHeader), bytesBegin)) { tie(header, bytesBegin) = MessageHeader::fromNetworkByteStream( bytesBegin + protocolHeaderSize, bytesEnd); } return make_pair(move(header), move(bytesBegin)); } } // namespace v1 } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/PeerGateways.hpp0000644000175000017500000001525012765602651023776 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace discovery { // GatewayFactory must have an operator()(NodeState, IoRef, asio::ip::address) // that constructs a new PeerGateway on a given interface address. template class PeerGateways { public: using IoType = typename util::Injected::type; using Gateway = typename std::result_of, asio::ip::address)>::type; using GatewayMap = std::map; PeerGateways(const std::chrono::seconds rescanPeriod, NodeState state, GatewayFactory factory, util::Injected io) : mIo(std::move(io)) { mpScannerCallback = std::make_shared(std::move(state), std::move(factory), *mIo); mpScanner = std::make_shared( rescanPeriod, util::injectShared(mpScannerCallback), util::injectRef(*mIo)); } ~PeerGateways() { // Release the callback in the io thread so that gateway cleanup // doesn't happen in the client thread mIo->async(Deleter{*this}); } PeerGateways(const PeerGateways&) = delete; PeerGateways& operator=(const PeerGateways&) = delete; PeerGateways(PeerGateways&&) = delete; PeerGateways& operator=(PeerGateways&&) = delete; void enable(const bool bEnable) { auto pCallback = mpScannerCallback; auto pScanner = mpScanner; if (pCallback && pScanner) { mIo->async([pCallback, pScanner, bEnable] { pCallback->mGateways.clear(); pScanner->enable(bEnable); }); } } template void withGatewaysAsync(Handler handler) { auto pCallback = mpScannerCallback; if (pCallback) { mIo->async([pCallback, handler] { handler(pCallback->mGateways.begin(), pCallback->mGateways.end()); }); } } void updateNodeState(const NodeState& state) { auto pCallback = mpScannerCallback; if (pCallback) { mIo->async([pCallback, state] { pCallback->mState = state; for (const auto& entry : pCallback->mGateways) { entry.second->updateNodeState(state); } }); } } // If a gateway has become non-responsive or is throwing exceptions, // this method can be invoked to either fix it or discard it. void repairGateway(const asio::ip::address& gatewayAddr) { auto pCallback = mpScannerCallback; auto pScanner = mpScanner; if (pCallback && pScanner) { mIo->async([pCallback, pScanner, gatewayAddr] { if (pCallback->mGateways.erase(gatewayAddr)) { // If we erased a gateway, rescan again immediately so that // we will re-initialize it if it's still present pScanner->scan(); } }); } } private: struct Callback { Callback(NodeState state, GatewayFactory factory, IoType& io) : mState(std::move(state)) , mFactory(std::move(factory)) , mIo(io) { } template void operator()(const AddrRange& range) { using namespace std; // Get the set of current addresses. vector curAddrs; curAddrs.reserve(mGateways.size()); transform(std::begin(mGateways), std::end(mGateways), back_inserter(curAddrs), [](const typename GatewayMap::value_type& vt) { return vt.first; }); // Now use set_difference to determine the set of addresses that // are new and the set of cur addresses that are no longer there vector newAddrs; set_difference(std::begin(range), std::end(range), std::begin(curAddrs), std::end(curAddrs), back_inserter(newAddrs)); vector staleAddrs; set_difference(std::begin(curAddrs), std::end(curAddrs), std::begin(range), std::end(range), back_inserter(staleAddrs)); // Remove the stale addresses for (const auto& addr : staleAddrs) { mGateways.erase(addr); } // Add the new addresses for (const auto& addr : newAddrs) { try { // Only handle v4 for now if (addr.is_v4()) { info(mIo.log()) << "initializing peer gateway on interface " << addr; mGateways.emplace(addr, mFactory(mState, util::injectRef(mIo), addr.to_v4())); } } catch (const runtime_error& e) { warning(mIo.log()) << "failed to init gateway on interface " << addr << " reason: " << e.what(); } } } NodeState mState; GatewayFactory mFactory; IoType& mIo; GatewayMap mGateways; }; using Scanner = InterfaceScanner, IoType&>; struct Deleter { Deleter(PeerGateways& gateways) : mpScannerCallback(std::move(gateways.mpScannerCallback)) , mpScanner(std::move(gateways.mpScanner)) { } void operator()() { mpScanner.reset(); mpScannerCallback.reset(); } std::shared_ptr mpScannerCallback; std::shared_ptr mpScanner; }; std::shared_ptr mpScannerCallback; std::shared_ptr mpScanner; util::Injected mIo; }; // Factory function template std::unique_ptr> makePeerGateways( const std::chrono::seconds rescanPeriod, NodeState state, GatewayFactory factory, util::Injected io) { using namespace std; using Gateways = PeerGateways; return unique_ptr{ new Gateways{rescanPeriod, move(state), move(factory), move(io)}}; } } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/InterfaceScanner.hpp0000644000175000017500000000543512765602651024614 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include namespace ableton { namespace discovery { // Callback takes a range of asio::ip:address which is // guaranteed to be sorted and unique template class InterfaceScanner { public: using Timer = typename util::Injected::type::Timer; InterfaceScanner(const std::chrono::seconds period, util::Injected callback, util::Injected io) : mPeriod(period) , mCallback(std::move(callback)) , mIo(std::move(io)) , mTimer(mIo->makeTimer()) { } void enable(const bool bEnable) { if (bEnable) { scan(); } else { mTimer.cancel(); } } void scan() { using namespace std; debug(mIo->log()) << "Scanning network interfaces"; // Rescan the hardware for available network interface addresses vector addrs = mIo->scanNetworkInterfaces(); // Sort and unique them to guarantee consistent comparison sort(begin(addrs), end(addrs)); addrs.erase(unique(begin(addrs), end(addrs)), end(addrs)); // Pass them to the callback (*mCallback)(std::move(addrs)); // setup the next scanning mTimer.expires_from_now(mPeriod); using ErrorCode = typename Timer::ErrorCode; mTimer.async_wait([this](const ErrorCode e) { if (!e) { scan(); } }); } private: const std::chrono::seconds mPeriod; util::Injected mCallback; util::Injected mIo; Timer mTimer; }; // Factory function template InterfaceScanner makeInterfaceScanner( const std::chrono::seconds period, util::Injected callback, util::Injected io) { using namespace std; return {period, move(callback), move(io)}; } } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/test/0000755000175000017500000000000012765602651021641 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/discovery/test/PayloadEntries.hpp0000644000175000017500000000501012765602651025271 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace discovery { namespace test { // Test payload entries // A fixed-size entry type struct Foo { enum { key = '_foo' }; std::int32_t fooVal; friend std::uint32_t sizeInByteStream(const Foo& foo) { // Namespace qualification is needed to avoid ambiguous function definitions return discovery::sizeInByteStream(foo.fooVal); } template friend It toNetworkByteStream(const Foo& foo, It out) { return discovery::toNetworkByteStream(foo.fooVal, std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { auto result = Deserialize::fromNetworkByteStream( std::move(begin), std::move(end)); return std::make_pair(Foo{std::move(result.first)}, std::move(result.second)); } }; // A variable-size entry type struct Bar { enum { key = '_bar' }; std::vector barVals; friend std::uint32_t sizeInByteStream(const Bar& bar) { return discovery::sizeInByteStream(bar.barVals); } template friend It toNetworkByteStream(const Bar& bar, It out) { return discovery::toNetworkByteStream(bar.barVals, out); } template static std::pair fromNetworkByteStream(It begin, It end) { auto result = Deserialize::fromNetworkByteStream( std::move(begin), std::move(end)); return std::make_pair(Bar{std::move(result.first)}, std::move(result.second)); } }; } // namespace test } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/test/Interface.hpp0000644000175000017500000000414312765602651024254 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace discovery { namespace test { class Interface { public: void send(const uint8_t* const bytes, const size_t numBytes, const asio::ip::udp::endpoint& endpoint) { sentMessages.push_back( std::make_pair(std::vector{bytes, bytes + numBytes}, endpoint)); } template void receive(Callback callback, Tag tag) { mCallback = [callback, tag]( const asio::ip::udp::endpoint& from, const std::vector& buffer) { callback(tag, from, begin(buffer), end(buffer)); }; } template void incomingMessage( const asio::ip::udp::endpoint& from, It messageBegin, It messageEnd) { std::vector buffer{messageBegin, messageEnd}; mCallback(from, buffer); } asio::ip::udp::endpoint endpoint() const { return asio::ip::udp::endpoint({}, 0); } using SentMessage = std::pair, asio::ip::udp::endpoint>; std::vector sentMessages; private: using ReceiveCallback = std::function&)>; ReceiveCallback mCallback; }; } // namespace test } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/test/Socket.hpp0000644000175000017500000000442712765602651023611 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace discovery { namespace test { class Socket { public: Socket(util::test::IoService&) { } friend void configureUnicastSocket(Socket&, const asio::ip::address_v4&) { } std::size_t send( const uint8_t* const pData, const size_t numBytes, const asio::ip::udp::endpoint& to) { sentMessages.push_back( std::make_pair(std::vector{pData, pData + numBytes}, to)); return numBytes; } template void receive(Handler handler) { mCallback = [handler](const asio::ip::udp::endpoint& from, const std::vector& buffer) { handler(from, begin(buffer), end(buffer)); }; } template void incomingMessage( const asio::ip::udp::endpoint& from, It messageBegin, It messageEnd) { std::vector buffer{messageBegin, messageEnd}; mCallback(from, buffer); } asio::ip::udp::endpoint endpoint() const { return asio::ip::udp::endpoint({}, 0); } using SentMessage = std::pair, asio::ip::udp::endpoint>; std::vector sentMessages; private: using ReceiveCallback = std::function&)>; ReceiveCallback mCallback; }; } // namespace test } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/Payload.hpp0000644000175000017500000001756112765602651022776 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace discovery { struct PayloadEntryHeader { using Key = std::uint32_t; using Size = std::uint32_t; Key key; Size size; friend Size sizeInByteStream(const PayloadEntryHeader& header) { return sizeInByteStream(header.key) + sizeInByteStream(header.size); } template friend It toNetworkByteStream(const PayloadEntryHeader& header, It out) { return toNetworkByteStream( header.size, toNetworkByteStream(header.key, std::move(out))); } template static std::pair fromNetworkByteStream(It begin, const It end) { using namespace std; Key key; Size size; tie(key, begin) = Deserialize::fromNetworkByteStream(begin, end); tie(size, begin) = Deserialize::fromNetworkByteStream(begin, end); return make_pair(PayloadEntryHeader{move(key), move(size)}, move(begin)); } }; template struct PayloadEntry { PayloadEntry(EntryType entryVal) : value(std::move(entryVal)) { header = {EntryType::key, sizeInByteStream(value)}; } PayloadEntryHeader header; EntryType value; friend std::uint32_t sizeInByteStream(const PayloadEntry& entry) { return sizeInByteStream(entry.header) + sizeInByteStream(entry.value); } template friend It toNetworkByteStream(const PayloadEntry& entry, It out) { return toNetworkByteStream( entry.value, toNetworkByteStream(entry.header, std::move(out))); } }; namespace detail { template using HandlerMap = std::unordered_map>; // Given an index of handlers and a byte range, parse the bytes as a // sequence of payload entries and invoke the appropriate handler for // each entry type. Entries that are encountered that do not have a // corresponding handler in the map are ignored. Throws // std::runtime_error if parsing fails for any entry. Note that if an // exception is thrown, some of the handlers may have already been called. template void parseByteStream(HandlerMap& map, It bsBegin, const It bsEnd) { using namespace std; while (bsBegin < bsEnd) { // Try to parse an entry header at this location in the byte stream PayloadEntryHeader header; It valueBegin; tie(header, valueBegin) = Deserialize::fromNetworkByteStream(bsBegin, bsEnd); // Ensure that the reported size of the entry does not exceed the // length of the byte stream It valueEnd = valueBegin + header.size; if (bsEnd < valueEnd) { throw range_error("Partial payload entry with key: " + to_string(header.key)); } // The next entry will start at the end of this one bsBegin = valueEnd; // Use the appropriate handler for this entry, if available auto handlerIt = map.find(header.key); if (handlerIt != end(map)) { handlerIt->second(move(valueBegin), move(valueEnd)); } } } } // namespace detail // Payload encoding template struct Payload; template struct Payload { Payload(First first, Rest rest) : mFirst(std::move(first)) , mRest(std::move(rest)) { } Payload(PayloadEntry first, Rest rest) : mFirst(std::move(first)) , mRest(std::move(rest)) { } template using PayloadSum = Payload>; // Concatenate payloads together into a single payload template friend PayloadSum operator+( Payload lhs, Payload rhs) { return {std::move(lhs.mFirst), std::move(lhs.mRest) + std::move(rhs)}; } friend std::size_t sizeInByteStream(const Payload& payload) { return sizeInByteStream(payload.mFirst) + sizeInByteStream(payload.mRest); } template friend It toNetworkByteStream(const Payload& payload, It streamIt) { return toNetworkByteStream( payload.mRest, toNetworkByteStream(payload.mFirst, std::move(streamIt))); } PayloadEntry mFirst; Rest mRest; }; template <> struct Payload<> { template using PayloadSum = Payload; template friend PayloadSum operator+(Payload, Payload rhs) { return rhs; } friend std::size_t sizeInByteStream(const Payload&) { return 0; } template friend It toNetworkByteStream(const Payload&, It streamIt) { return streamIt; } }; template struct PayloadBuilder; // Payload factory function template auto makePayload(Entries... entries) -> decltype(PayloadBuilder{}(std::move(entries)...)) { return PayloadBuilder{}(std::move(entries)...); } template struct PayloadBuilder { auto operator()(First first, Rest... rest) -> Payload { return {std::move(first), makePayload(std::move(rest)...)}; } }; template <> struct PayloadBuilder<> { Payload<> operator()() { return {}; } }; // Parse payloads to values template struct ParsePayload; template struct ParsePayload { template static void parse(It begin, It end, Handlers... handlers) { detail::HandlerMap map; collectHandlers(map, std::move(handlers)...); detail::parseByteStream(map, std::move(begin), std::move(end)); } template static void collectHandlers( detail::HandlerMap& map, FirstHandler handler, RestHandlers... rest) { using namespace std; map[First::key] = [handler](const It begin, const It end) { const auto res = First::fromNetworkByteStream(begin, end); if (res.second != end) { std::ostringstream stringStream; stringStream << "Parsing payload entry " << First::key << " did not consume the expected number of bytes. " << " Expected: " << distance(begin, end) << ", Actual: " << distance(begin, res.second); throw range_error(stringStream.str()); } handler(res.first); }; ParsePayload::collectHandlers(map, std::move(rest)...); } }; template <> struct ParsePayload<> { template static void collectHandlers(detail::HandlerMap&) { } }; template void parsePayload(It begin, It end, Handlers... handlers) { using namespace std; ParsePayload::parse(move(begin), move(end), move(handlers)...); } } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/MessageTypes.hpp0000644000175000017500000000274212765602651024011 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once namespace ableton { namespace discovery { // Message types used in the Ableton service discovery protocol. There // are two logical messages: a state dump and a bye bye. // // A state dump provides all relevant information about the peer's // current state as well as a Time To Live (TTL) value that indicates // how many seconds this state should be considered valid. // // The bye bye indicates that the sender is leaving the session. template struct PeerState { NodeState peerState; int ttl; }; template struct ByeBye { NodeId peerId; }; } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/Service.hpp0000644000175000017500000000411412765602651022773 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace discovery { template class Service { public: using ServicePeerGateways = PeerGateways; Service(NodeState state, GatewayFactory factory, util::Injected io) : mGateways( std::chrono::seconds(5), std::move(state), std::move(factory), std::move(io)) { } void enable(const bool bEnable) { mGateways.enable(bEnable); } // Asynchronously operate on the current set of peer gateways. The // handler will be invoked in the service's io context. template void withGatewaysAsync(Handler handler) { mGateways.withGatewaysAsync(std::move(handler)); } void updateNodeState(const NodeState& state) { mGateways.updateNodeState(state); } // Repair the gateway with the given address if possible. Its // sockets may have been closed, for example, and the gateway needs // to be regenerated. void repairGateway(const asio::ip::address& gatewayAddr) { mGateways.repairGateway(gatewayAddr); } private: ServicePeerGateways mGateways; }; } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/NetworkByteStreamSerializable.hpp0000644000175000017500000002576512765602651027372 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #if LINK_PLATFORM_MACOSX #include #elif LINK_PLATFORM_LINUX #include #endif #include #include #include #include #include #if LINK_PLATFORM_WINDOWS #include #include #include #endif namespace ableton { namespace discovery { // Concept: NetworkByteStreamSerializable // // A type that can be encoded to a stream of bytes and decoded from a // stream of bytes in network byte order. The following type is for // documentation purposes only. struct NetworkByteStreamSerializable { friend std::uint32_t sizeInByteStream(const NetworkByteStreamSerializable&); // The byte stream pointed to by 'out' must have sufficient space to // hold this object, as defined by sizeInByteStream. template friend It toNetworkByteStream(const NetworkByteStreamSerializable&, It out); }; // Deserialization aspect of the concept. Outside of the demonstration // type above because clients must specify the type // explicitly. Default implementation just defers to a class static // method on T. For types that can't provide such a method, specialize // this template. template struct Deserialize { // Throws std::runtime_exception if parsing the type from the given // byte range fails. Returns a pair of the correctly parsed value // and an iterator to the next byte to parse. template static std::pair fromNetworkByteStream(It begin, It end) { return T::fromNetworkByteStream(std::move(begin), std::move(end)); } }; // Default size implementation. Works for primitive types. template std::uint32_t sizeInByteStream(T) { return sizeof(T); } namespace detail { // utilities for implementing concept for primitive types template It copyToByteStream(T t, It out) { using namespace std; return copy_n( reinterpret_cast::pointer>(&t), sizeof(t), out); } template std::pair copyFromByteStream(It begin, const It end) { using namespace std; using ItDiff = typename iterator_traits::difference_type; if (distance(begin, end) < static_cast(sizeof(T))) { throw range_error("Parsing type from byte stream failed"); } else { T t; const auto n = sizeof(t); copy_n(begin, n, reinterpret_cast(&t)); return make_pair(t, begin + n); } } } // namespace detail // Model the concept for unsigned integral types // uint8_t template It toNetworkByteStream(const uint8_t byte, It out) { return detail::copyToByteStream(byte, std::move(out)); } template <> struct Deserialize { template static std::pair fromNetworkByteStream(It begin, It end) { return detail::copyFromByteStream(std::move(begin), std::move(end)); } }; // uint16_t template It toNetworkByteStream(uint16_t s, It out) { return detail::copyToByteStream(htons(s), std::move(out)); } template <> struct Deserialize { template static std::pair fromNetworkByteStream(It begin, It end) { auto result = detail::copyFromByteStream(std::move(begin), std::move(end)); result.first = ntohs(result.first); return result; } }; // uint32_t template It toNetworkByteStream(uint32_t l, It out) { return detail::copyToByteStream(htonl(l), std::move(out)); } template <> struct Deserialize { template static std::pair fromNetworkByteStream(It begin, It end) { auto result = detail::copyFromByteStream(std::move(begin), std::move(end)); result.first = ntohl(result.first); return result; } }; // int32_t in terms of uint32_t template It toNetworkByteStream(int32_t l, It out) { return toNetworkByteStream(reinterpret_cast(l), std::move(out)); } template <> struct Deserialize { template static std::pair fromNetworkByteStream(It begin, It end) { auto result = Deserialize::fromNetworkByteStream(std::move(begin), std::move(end)); return std::make_pair(reinterpret_cast(result.first), result.second); } }; // uint64_t template It toNetworkByteStream(uint64_t ll, It out) { return detail::copyToByteStream(htonll(ll), std::move(out)); } template <> struct Deserialize { template static std::pair fromNetworkByteStream(It begin, It end) { auto result = detail::copyFromByteStream(std::move(begin), std::move(end)); result.first = ntohll(result.first); return result; } }; // int64_t in terms of uint64_t template It toNetworkByteStream(int64_t ll, It out) { return toNetworkByteStream(reinterpret_cast(ll), std::move(out)); } template <> struct Deserialize { template static std::pair fromNetworkByteStream(It begin, It end) { auto result = Deserialize::fromNetworkByteStream(std::move(begin), std::move(end)); return std::make_pair(reinterpret_cast(result.first), result.second); } }; // overloads for std::chrono durations template std::uint32_t sizeInByteStream(const std::chrono::duration dur) { return sizeInByteStream(dur.count()); } template It toNetworkByteStream(const std::chrono::duration dur, It out) { return toNetworkByteStream(dur.count(), std::move(out)); } template struct Deserialize> { template static std::pair, It> fromNetworkByteStream( It begin, It end) { using namespace std; auto result = Deserialize::fromNetworkByteStream(move(begin), move(end)); return make_pair(std::chrono::duration{result.first}, result.second); } }; namespace detail { // Generic serialize/deserialize utilities for containers template std::uint32_t containerSizeInByteStream(const Container& container) { std::uint32_t totalSize = 0; for (const auto& val : container) { totalSize += sizeInByteStream(val); } return totalSize; } template It containerToNetworkByteStream(const Container& container, It out) { for (const auto& val : container) { out = toNetworkByteStream(val, out); } return out; } template BytesIt deserializeContainer(BytesIt bytesBegin, const BytesIt bytesEnd, InsertIt contBegin, const std::uint32_t maxElements) { using namespace std; std::uint32_t numElements = 0; while (bytesBegin < bytesEnd && numElements < maxElements) { T newVal; tie(newVal, bytesBegin) = Deserialize::fromNetworkByteStream(bytesBegin, bytesEnd); *contBegin++ = newVal; ++numElements; } return bytesBegin; } } // detail // Need specific overloads for each container type, but use above // utilities for common implementation // array template std::uint32_t sizeInByteStream(const std::array& arr) { return detail::containerSizeInByteStream(arr); } template It toNetworkByteStream(const std::array& arr, It out) { return detail::containerToNetworkByteStream(arr, std::move(out)); } template struct Deserialize> { template static std::pair, It> fromNetworkByteStream(It begin, It end) { using namespace std; array result{}; auto resultIt = detail::deserializeContainer(move(begin), move(end), move(result.begin()), Size); return make_pair(move(result), move(resultIt)); } }; // vector template std::uint32_t sizeInByteStream(const std::vector& vec) { return detail::containerSizeInByteStream(vec); } template It toNetworkByteStream(const std::vector& vec, It out) { return detail::containerToNetworkByteStream(vec, std::move(out)); } template struct Deserialize> { template static std::pair, It> fromNetworkByteStream( It bytesBegin, It bytesEnd) { using namespace std; vector result; // Use the number of bytes remaining in the stream as the upper // bound on the number of elements that could be deserialized // since we don't have a better heuristic. auto resultIt = detail::deserializeContainer(move(bytesBegin), move(bytesEnd), back_inserter(result), static_cast(distance(bytesBegin, bytesEnd))); return make_pair(move(result), move(resultIt)); } }; // 3-tuple template std::uint32_t sizeInByteStream(const std::tuple& tup) { return sizeInByteStream(std::get<0>(tup)) + sizeInByteStream(std::get<1>(tup)) + sizeInByteStream(std::get<2>(tup)); } template It toNetworkByteStream(const std::tuple& tup, It out) { return toNetworkByteStream( std::get<2>(tup), toNetworkByteStream(std::get<1>(tup), toNetworkByteStream(std::get<0>(tup), std::move(out)))); } template struct Deserialize> { template static std::pair, It> fromNetworkByteStream(It begin, It end) { using namespace std; auto xres = Deserialize::fromNetworkByteStream(begin, end); auto yres = Deserialize::fromNetworkByteStream(xres.second, end); auto zres = Deserialize::fromNetworkByteStream(yres.second, end); return make_pair( std::tuple{move(xres.first), move(yres.first), move(zres.first)}, move(zres.second)); } }; } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/IpV4Interface.hpp0000644000175000017500000000643412765602651024005 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace discovery { inline asio::ip::udp::endpoint multicastEndpoint() { return {asio::ip::address::from_string("224.76.78.75"), 20808}; } // Type tags for dispatching between unicast and multicast packets struct MulticastTag { }; struct UnicastTag { }; template class IpV4Interface { public: using Socket = typename util::Injected::type::template Socket; IpV4Interface(util::Injected io, const asio::ip::address_v4& addr) : mIo(std::move(io)) , mMulticastReceiveSocket(mIo->template openMulticastSocket(addr)) , mSendSocket(mIo->template openUnicastSocket(addr)) { } IpV4Interface(const IpV4Interface&) = delete; IpV4Interface& operator=(const IpV4Interface&) = delete; IpV4Interface(IpV4Interface&& rhs) : mIo(std::move(rhs.mIo)) , mMulticastReceiveSocket(std::move(rhs.mMulticastReceiveSocket)) , mSendSocket(std::move(rhs.mSendSocket)) { } std::size_t send( const uint8_t* const pData, const size_t numBytes, const asio::ip::udp::endpoint& to) { return mSendSocket.send(pData, numBytes, to); } template void receive(Handler handler, UnicastTag) { mSendSocket.receive(SocketReceiver{std::move(handler)}); } template void receive(Handler handler, MulticastTag) { mMulticastReceiveSocket.receive( SocketReceiver(std::move(handler))); } asio::ip::udp::endpoint endpoint() const { return mSendSocket.endpoint(); } private: template struct SocketReceiver { SocketReceiver(Handler handler) : mHandler(std::move(handler)) { } template void operator()( const asio::ip::udp::endpoint& from, const It messageBegin, const It messageEnd) { mHandler(Tag{}, from, messageBegin, messageEnd); } Handler mHandler; }; util::Injected mIo; Socket mMulticastReceiveSocket; Socket mSendSocket; }; template IpV4Interface makeIpV4Interface( util::Injected io, const asio::ip::address_v4& addr) { return {std::move(io), addr}; } } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/PeerGateway.hpp0000644000175000017500000001706412765602651023620 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include namespace ableton { namespace discovery { template class PeerGateway { public: // The peer types are defined by the observer but must match with those // used by the Messenger using ObserverT = typename util::Injected::type; using NodeState = typename ObserverT::GatewayObserverNodeState; using NodeId = typename ObserverT::GatewayObserverNodeId; using Timer = typename util::Injected::type::Timer; using TimerError = typename Timer::ErrorCode; PeerGateway(util::Injected messenger, util::Injected observer, util::Injected io) : mpImpl(new Impl(std::move(messenger), std::move(observer), std::move(io))) { mpImpl->listen(); } PeerGateway(const PeerGateway&) = delete; PeerGateway& operator=(const PeerGateway&) = delete; PeerGateway(PeerGateway&& rhs) : mpImpl(std::move(rhs.mpImpl)) { } void updateState(NodeState state) { mpImpl->updateState(std::move(state)); } private: using PeerTimeout = std::pair; using PeerTimeouts = std::vector; struct Impl : std::enable_shared_from_this { Impl(util::Injected messenger, util::Injected observer, util::Injected io) : mMessenger(std::move(messenger)) , mObserver(std::move(observer)) , mIo(std::move(io)) , mPruneTimer(mIo->makeTimer()) { } void updateState(NodeState state) { mMessenger->updateState(std::move(state)); try { mMessenger->broadcastState(); } catch (const std::runtime_error& err) { info(mIo->log()) << "State broadcast failed on gateway: " << err.what(); } } void listen() { mMessenger->receive(util::makeAsyncSafe(this->shared_from_this())); } // Operators for handling incoming messages void operator()(const PeerState& msg) { onPeerState(msg.peerState, msg.ttl); listen(); } void operator()(const ByeBye& msg) { onByeBye(msg.peerId); listen(); } void onPeerState(const NodeState& nodeState, const int ttl) { using namespace std; const auto peerId = nodeState.ident(); const auto existing = findPeer(peerId); if (existing != end(mPeerTimeouts)) { // If the peer is already present in our timeout list, remove it // as it will be re-inserted below. mPeerTimeouts.erase(existing); } auto newTo = make_pair(mPruneTimer.now() + std::chrono::seconds(ttl), peerId); mPeerTimeouts.insert( upper_bound(begin(mPeerTimeouts), end(mPeerTimeouts), newTo, TimeoutCompare{}), move(newTo)); sawPeer(*mObserver, nodeState); scheduleNextPruning(); } void onByeBye(const NodeId& peerId) { const auto it = findPeer(peerId); if (it != mPeerTimeouts.end()) { peerLeft(*mObserver, it->second); mPeerTimeouts.erase(it); } } void pruneExpiredPeers() { using namespace std; const auto test = make_pair(mPruneTimer.now(), NodeId{}); debug(mIo->log()) << "pruning peers @ " << test.first.time_since_epoch().count(); const auto endExpired = lower_bound(begin(mPeerTimeouts), end(mPeerTimeouts), test, TimeoutCompare{}); for_each(begin(mPeerTimeouts), endExpired, [this](const PeerTimeout& pto) { info(mIo->log()) << "pruning peer " << pto.second; peerTimedOut(*mObserver, pto.second); }); mPeerTimeouts.erase(begin(mPeerTimeouts), endExpired); scheduleNextPruning(); } void scheduleNextPruning() { // Find the next peer to expire and set the timer based on it if (!mPeerTimeouts.empty()) { // Add a second of padding to the timer to avoid over-eager timeouts const auto t = mPeerTimeouts.front().first + std::chrono::seconds(1); debug(mIo->log()) << "scheduling next pruning for " << t.time_since_epoch().count() << " because of peer " << mPeerTimeouts.front().second; mPruneTimer.expires_at(t); mPruneTimer.async_wait([this](const TimerError e) { if (!e) { pruneExpiredPeers(); } }); } } struct TimeoutCompare { bool operator()(const PeerTimeout& lhs, const PeerTimeout& rhs) const { return lhs.first < rhs.first; } }; typename PeerTimeouts::iterator findPeer(const NodeId& peerId) { return std::find_if(begin(mPeerTimeouts), end(mPeerTimeouts), [&peerId](const PeerTimeout& pto) { return pto.second == peerId; }); } util::Injected mMessenger; util::Injected mObserver; util::Injected mIo; Timer mPruneTimer; PeerTimeouts mPeerTimeouts; // Invariant: sorted by time_point }; std::shared_ptr mpImpl; }; template PeerGateway makePeerGateway( util::Injected messenger, util::Injected observer, util::Injected io) { return {std::move(messenger), std::move(observer), std::move(io)}; } // IpV4 gateway types template using IpV4Messenger = UdpMessenger::type&, v1::kMaxMessageSize>, StateQuery, IoContext>; template using IpV4Gateway = PeerGateway::type&>, PeerObserver, IoContext>; // Factory function to bind a PeerGateway to an IpV4Interface with the given address. template IpV4Gateway makeIpV4Gateway( util::Injected io, const asio::ip::address_v4& addr, util::Injected observer, NodeState state) { using namespace std; using namespace util; const uint8_t ttl = 5; const uint8_t ttlRatio = 20; auto iface = makeIpV4Interface(injectRef(*io), addr); auto messenger = makeUdpMessenger(injectVal(move(iface)), move(state), injectRef(*io), ttl, ttlRatio); return {injectVal(move(messenger)), move(observer), move(io)}; } } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/Socket.hpp0000644000175000017500000001051712765602651022627 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include namespace ableton { namespace discovery { template struct Socket { Socket(platforms::asio::AsioService& io) : mpImpl(std::make_shared(io)) { } Socket(const Socket&) = delete; Socket& operator=(const Socket&) = delete; Socket(Socket&& rhs) : mpImpl(std::move(rhs.mpImpl)) { } std::size_t send( const uint8_t* const pData, const size_t numBytes, const asio::ip::udp::endpoint& to) { assert(numBytes < MaxPacketSize); return mpImpl->mSocket.send_to(asio::buffer(pData, numBytes), to); } template void receive(Handler handler) { mpImpl->mHandler = std::move(handler); mpImpl->mSocket.async_receive_from( asio::buffer(mpImpl->mReceiveBuffer, MaxPacketSize), mpImpl->mSenderEndpoint, util::makeAsyncSafe(mpImpl)); } asio::ip::udp::endpoint endpoint() const { return mpImpl->mSocket.local_endpoint(); } struct Impl { Impl(platforms::asio::AsioService& io) : mSocket(io.mService, asio::ip::udp::v4()) { } ~Impl() { // Ignore error codes in shutdown and close as the socket may // have already been forcibly closed asio::error_code ec; mSocket.shutdown(asio::ip::udp::socket::shutdown_both, ec); mSocket.close(ec); } void operator()(const asio::error_code& error, const std::size_t numBytes) { if (!error && numBytes > 0 && numBytes <= MaxPacketSize) { const auto bufBegin = begin(mReceiveBuffer); mHandler(mSenderEndpoint, bufBegin, bufBegin + static_cast(numBytes)); } } asio::ip::udp::socket mSocket; asio::ip::udp::endpoint mSenderEndpoint; using Buffer = std::array; Buffer mReceiveBuffer; using ByteIt = typename Buffer::const_iterator; std::function mHandler; }; std::shared_ptr mpImpl; }; // Configure an asio socket for receiving multicast messages template void configureMulticastSocket(Socket& socket, const asio::ip::address_v4& addr, const asio::ip::udp::endpoint& multicastEndpoint) { socket.mpImpl->mSocket.set_option(asio::ip::udp::socket::reuse_address(true)); // ??? socket.mpImpl->mSocket.set_option(asio::socket_base::broadcast(!addr.is_loopback())); // ??? socket.mpImpl->mSocket.set_option( asio::ip::multicast::enable_loopback(addr.is_loopback())); socket.mpImpl->mSocket.set_option(asio::ip::multicast::outbound_interface(addr)); // Is from_string("0.0.0.0") best approach? socket.mpImpl->mSocket.bind( {asio::ip::address::from_string("0.0.0.0"), multicastEndpoint.port()}); socket.mpImpl->mSocket.set_option( asio::ip::multicast::join_group(multicastEndpoint.address().to_v4(), addr)); } // Configure an asio socket for receiving unicast messages template void configureUnicastSocket( Socket& socket, const asio::ip::address_v4& addr) { // ??? really necessary? socket.mpImpl->mSocket.set_option( asio::ip::multicast::enable_loopback(addr.is_loopback())); socket.mpImpl->mSocket.set_option(asio::ip::multicast::outbound_interface(addr)); socket.mpImpl->mSocket.bind(asio::ip::udp::endpoint{addr, 0}); } } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/discovery/UdpMessenger.hpp0000644000175000017500000002353512765602651024004 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include #include #include namespace ableton { namespace discovery { // An exception thrown when sending a udp message fails. Stores the // interface through which the sending failed. struct UdpSendException : std::runtime_error { UdpSendException(const std::runtime_error& e, asio::ip::address ifAddr) : std::runtime_error(e.what()) , interfaceAddr(std::move(ifAddr)) { } asio::ip::address interfaceAddr; }; // Throws UdpSendException template void sendUdpMessage(Interface& iface, NodeId from, const uint8_t ttl, const v1::MessageType messageType, const Payload& payload, const asio::ip::udp::endpoint& to) { using namespace std; v1::MessageBuffer buffer; const auto messageBegin = begin(buffer); const auto messageEnd = v1::detail::encodeMessage(move(from), ttl, messageType, payload, messageBegin); const auto numBytes = static_cast(distance(messageBegin, messageEnd)); try { iface.send(buffer.data(), numBytes, to); } catch (const std::runtime_error& err) { throw UdpSendException{err, iface.endpoint().address()}; } } // UdpMessenger uses a "shared_ptr pImpl" pattern to make it movable // and to support safe async handler callbacks when receiving messages // on the given interface. template class UdpMessenger { public: using NodeState = NodeStateT; using NodeId = typename NodeState::IdType; using Timer = typename util::Injected::type::Timer; using TimerError = typename Timer::ErrorCode; using TimePoint = typename Timer::TimePoint; UdpMessenger(util::Injected iface, NodeState state, util::Injected io, const uint8_t ttl, const uint8_t ttlRatio) : mpImpl(std::make_shared( std::move(iface), std::move(state), std::move(io), ttl, ttlRatio)) { // We need to always listen for incoming traffic in order to // respond to peer state broadcasts mpImpl->listen(MulticastTag{}); mpImpl->listen(UnicastTag{}); mpImpl->broadcastState(); } UdpMessenger(const UdpMessenger&) = delete; UdpMessenger& operator=(const UdpMessenger&) = delete; UdpMessenger(UdpMessenger&& rhs) : mpImpl(std::move(rhs.mpImpl)) { } ~UdpMessenger() { if (mpImpl != nullptr) { try { mpImpl->sendByeBye(); } catch (const UdpSendException& err) { debug(mpImpl->mIo->log()) << "Failed to send bye bye message: " << err.what(); } } } void updateState(NodeState state) { mpImpl->updateState(std::move(state)); } // Broadcast the current state of the system to all peers. May throw // std::runtime_error if assembling a broadcast message fails or if // there is an error at the transport layer. Throws on failure. void broadcastState() { mpImpl->broadcastState(); } // Asynchronous receive function for incoming messages from peers. Will // return immediately and the handler will be invoked when a message // is received. Handler must have operator() overloads for PeerState and // ByeBye messages. template void receive(Handler handler) { mpImpl->setReceiveHandler(std::move(handler)); } private: struct Impl : std::enable_shared_from_this { Impl(util::Injected iface, NodeState state, util::Injected io, const uint8_t ttl, const uint8_t ttlRatio) : mIo(std::move(io)) , mInterface(std::move(iface)) , mState(std::move(state)) , mTimer(mIo->makeTimer()) , mLastBroadcastTime{} , mTtl(ttl) , mTtlRatio(ttlRatio) , mPeerStateHandler([](PeerState) {}) , mByeByeHandler([](ByeBye) {}) { } template void setReceiveHandler(Handler handler) { mPeerStateHandler = [handler]( PeerState state) { handler(std::move(state)); }; mByeByeHandler = [handler](ByeBye byeBye) { handler(std::move(byeBye)); }; } void sendByeBye() { sendUdpMessage( *mInterface, mState.ident(), 0, v1::kByeBye, makePayload(), multicastEndpoint()); } void updateState(NodeState state) { mState = std::move(state); } void broadcastState() { using namespace std::chrono; const auto minBroadcastPeriod = milliseconds{50}; const auto nominalBroadcastPeriod = milliseconds(mTtl * 1000 / mTtlRatio); const auto timeSinceLastBroadcast = duration_cast(mTimer.now() - mLastBroadcastTime); // The rate is limited to maxBroadcastRate to prevent flooding the network. const auto delay = minBroadcastPeriod - timeSinceLastBroadcast; // Schedule the next broadcast before we actually send the // message so that if sending throws an exception we are still // scheduled to try again. We want to keep trying at our // interval as long as this instance is alive. mTimer.expires_from_now(delay > milliseconds{0} ? delay : nominalBroadcastPeriod); mTimer.async_wait([this](const TimerError e) { if (!e) { broadcastState(); } }); // If we're not delaying, broadcast now if (delay < milliseconds{1}) { debug(mIo->log()) << "Broadcasting state"; sendPeerState(v1::kAlive, multicastEndpoint()); } } void sendPeerState( const v1::MessageType messageType, const asio::ip::udp::endpoint& to) { sendUdpMessage( *mInterface, mState.ident(), mTtl, messageType, toPayload(mState), to); mLastBroadcastTime = mTimer.now(); } void sendResponse(const asio::ip::udp::endpoint& to) { sendPeerState(v1::kResponse, to); } template void listen(Tag tag) { mInterface->receive(util::makeAsyncSafe(this->shared_from_this()), tag); } template void operator()(Tag tag, const asio::ip::udp::endpoint& from, const It messageBegin, const It messageEnd) { auto result = v1::parseMessageHeader(messageBegin, messageEnd); const auto& header = result.first; // Ignore messages from self and other groups if (header.ident != mState.ident() && header.groupId == 0) { debug(mIo->log()) << "Received message type " << static_cast(header.messageType) << " from peer " << header.ident; switch (header.messageType) { case v1::kAlive: sendResponse(from); receivePeerState(std::move(result.first), result.second, messageEnd); break; case v1::kResponse: receivePeerState(std::move(result.first), result.second, messageEnd); break; case v1::kByeBye: receiveByeBye(std::move(result.first.ident)); break; default: info(mIo->log()) << "Unknown message received of type: " << header.messageType; } } listen(tag); } template void receivePeerState( v1::MessageHeader header, It payloadBegin, It payloadEnd) { try { auto state = NodeState::fromPayload( std::move(header.ident), std::move(payloadBegin), std::move(payloadEnd)); // Handlers must only be called once auto handler = std::move(mPeerStateHandler); mPeerStateHandler = [](PeerState) {}; handler(PeerState{std::move(state), header.ttl}); } catch (const std::runtime_error& err) { info(mIo->log()) << "Ignoring peer state message: " << err.what(); } } void receiveByeBye(NodeId nodeId) { // Handlers must only be called once auto byeByeHandler = std::move(mByeByeHandler); mByeByeHandler = [](ByeBye) {}; byeByeHandler(ByeBye{std::move(nodeId)}); } util::Injected mIo; util::Injected mInterface; NodeState mState; Timer mTimer; TimePoint mLastBroadcastTime; uint8_t mTtl; uint8_t mTtlRatio; std::function)> mPeerStateHandler; std::function)> mByeByeHandler; }; std::shared_ptr mpImpl; }; // Factory function template UdpMessenger makeUdpMessenger( util::Injected iface, NodeState state, util::Injected io, const uint8_t ttl, const uint8_t ttlRatio) { return UdpMessenger{ std::move(iface), std::move(state), std::move(io), ttl, ttlRatio}; } } // namespace discovery } // namespace ableton link-Link-1.0.0/include/ableton/Link.ipp0000644000175000017500000001205412765602651020264 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { inline Link::Link(const double bpm) : mPeerCountCallback([](std::size_t) { }) , mTempoCallback([](link::Tempo) { }) , mClock{} , mController(link::Tempo(bpm), [this](const std::size_t peers) { std::lock_guard lock(mCallbackMutex); mPeerCountCallback(peers); }, [this](const link::Tempo tempo) { std::lock_guard lock(mCallbackMutex); mTempoCallback(tempo); }, mClock, util::injectVal(link::platform::IoContext{})) { } inline bool Link::isEnabled() const { return mController.isEnabled(); } inline void Link::enable(const bool bEnable) { mController.enable(bEnable); } inline std::size_t Link::numPeers() const { return mController.numPeers(); } template void Link::setNumPeersCallback(Callback callback) { std::lock_guard lock(mCallbackMutex); mPeerCountCallback = [callback](const std::size_t numPeers) { callback(numPeers); }; } template void Link::setTempoCallback(Callback callback) { std::lock_guard lock(mCallbackMutex); mTempoCallback = [callback](const link::Tempo tempo) { callback(tempo.bpm()); }; } inline Link::Clock Link::clock() const { return mClock; } inline Link::Timeline Link::captureAudioTimeline() const { return Link::Timeline{mController.timelineRtSafe(), numPeers() > 0}; } inline void Link::commitAudioTimeline(const Link::Timeline timeline) { if (timeline.mOriginalTimeline != timeline.mTimeline) { mController.setTimelineRtSafe(timeline.mTimeline, mClock.micros()); } } inline Link::Timeline Link::captureAppTimeline() const { return Link::Timeline{mController.timeline(), numPeers() > 0}; } inline void Link::commitAppTimeline(const Link::Timeline timeline) { if (timeline.mOriginalTimeline != timeline.mTimeline) { mController.setTimeline(timeline.mTimeline, mClock.micros()); } } // Link::Timeline inline Link::Timeline::Timeline(const link::Timeline timeline, const bool bRespectQuantum) : mOriginalTimeline(timeline) , mbRespectQuantum(bRespectQuantum) , mTimeline(timeline) { } inline double Link::Timeline::tempo() const { return mTimeline.tempo.bpm(); } inline void Link::Timeline::setTempo( const double bpm, const std::chrono::microseconds atTime) { const auto desiredTl = link::clampTempo(link::Timeline{link::Tempo(bpm), mTimeline.toBeats(atTime), atTime}); mTimeline.tempo = desiredTl.tempo; mTimeline.timeOrigin = desiredTl.fromBeats(mTimeline.beatOrigin); } inline double Link::Timeline::beatAtTime( const std::chrono::microseconds time, const double quantum) const { return link::toPhaseEncodedBeats(mTimeline, time, link::Beats{quantum}).floating(); } inline double Link::Timeline::phaseAtTime( const std::chrono::microseconds time, const double quantum) const { return link::phase(link::Beats{beatAtTime(time, quantum)}, link::Beats{quantum}) .floating(); } inline std::chrono::microseconds Link::Timeline::timeAtBeat( const double beat, const double quantum) const { return link::fromPhaseEncodedBeats(mTimeline, link::Beats{beat}, link::Beats{quantum}); } inline void Link::Timeline::requestBeatAtTime( const double beat, std::chrono::microseconds time, const double quantum) { if (mbRespectQuantum) { time = timeAtBeat(link::nextPhaseMatch(link::Beats{beatAtTime(time, quantum)}, link::Beats{beat}, link::Beats{quantum}) .floating(), quantum); } forceBeatAtTime(beat, time, quantum); } inline void Link::Timeline::forceBeatAtTime( const double beat, const std::chrono::microseconds time, const double quantum) { // There are two components to the beat adjustment: a phase shift // and a beat magnitude adjustment. const auto curBeatAtTime = link::Beats{beatAtTime(time, quantum)}; const auto closestInPhase = link::closestPhaseMatch(curBeatAtTime, link::Beats{beat}, link::Beats{quantum}); mTimeline = shiftClientTimeline(mTimeline, closestInPhase - curBeatAtTime); // Now adjust the magnitude mTimeline.beatOrigin = mTimeline.beatOrigin + (link::Beats{beat} - closestInPhase); } } // ableton link-Link-1.0.0/include/ableton/link/0000755000175000017500000000000012765602651017610 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/link/PayloadEntries.hpp0000644000175000017500000000717412765602651023255 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace link { struct HostTime { enum { key = '__ht' }; HostTime() = default; HostTime(const std::chrono::microseconds tm) : time(tm) { } // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const HostTime& sht) { return discovery::sizeInByteStream(std::move(sht.time)); } template friend It toNetworkByteStream(const HostTime& sht, It out) { return discovery::toNetworkByteStream(std::move(sht.time), std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { using namespace std; auto result = discovery::Deserialize::fromNetworkByteStream( move(begin), move(end)); return make_pair(HostTime{move(result.first)}, move(result.second)); } std::chrono::microseconds time; }; struct GHostTime : HostTime { enum { key = '__gt' }; GHostTime() = default; GHostTime(const std::chrono::microseconds tm) : time(tm) { } // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const GHostTime& dgt) { return discovery::sizeInByteStream(std::move(dgt.time)); } template friend It toNetworkByteStream(const GHostTime& dgt, It out) { return discovery::toNetworkByteStream(std::move(dgt.time), std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { using namespace std; auto result = discovery::Deserialize::fromNetworkByteStream( move(begin), move(end)); return make_pair(GHostTime{move(result.first)}, move(result.second)); } std::chrono::microseconds time; }; struct PrevGHostTime { enum { key = '_pgt' }; PrevGHostTime() = default; PrevGHostTime(const std::chrono::microseconds tm) : time(tm) { } // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const PrevGHostTime& dgt) { return discovery::sizeInByteStream(std::move(dgt.time)); } template friend It toNetworkByteStream(const PrevGHostTime& pdgt, It out) { return discovery::toNetworkByteStream(std::move(pdgt.time), std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { using namespace std; auto result = discovery::Deserialize::fromNetworkByteStream( move(begin), move(end)); return make_pair(PrevGHostTime{move(result.first)}, move(result.second)); } std::chrono::microseconds time; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Tempo.hpp0000644000175000017500000000505612765602651021413 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace link { struct Tempo : std::tuple { Tempo() = default; // Beats per minute explicit Tempo(const double bpm) : std::tuple(bpm) { } Tempo(const std::chrono::microseconds microsPerBeat) : std::tuple(60. * 1e6 / microsPerBeat.count()) { } double bpm() const { return std::get<0>(*this); } std::chrono::microseconds microsPerBeat() const { return std::chrono::microseconds{std::llround(60. * 1e6 / bpm())}; } // Given the tempo, convert a time to a beat value Beats microsToBeats(const std::chrono::microseconds micros) const { return Beats{micros.count() / static_cast(microsPerBeat().count())}; } // Given the tempo, convert a beat to a time value std::chrono::microseconds beatsToMicros(const Beats beats) const { return std::chrono::microseconds{ std::llround(beats.floating() * microsPerBeat().count())}; } // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const Tempo tempo) { return discovery::sizeInByteStream(tempo.microsPerBeat()); } template friend It toNetworkByteStream(const Tempo tempo, It out) { return discovery::toNetworkByteStream(tempo.microsPerBeat(), std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { auto result = discovery::Deserialize::fromNetworkByteStream( std::move(begin), std::move(end)); return std::make_pair(Tempo{std::move(result.first)}, std::move(result.second)); } }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/v1/0000755000175000017500000000000012765602651020136 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/link/v1/Messages.hpp0000644000175000017500000001022412765602651022415 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace link { namespace v1 { // The maximum size of a message, in bytes const std::size_t kMaxMessageSize = 512; // Utility typedef for an array of bytes of maximum message size using MessageBuffer = std::array; using MessageType = uint8_t; const MessageType kPing = 1; const MessageType kPong = 2; struct MessageHeader { MessageType messageType; friend std::uint32_t sizeInByteStream(const MessageHeader& header) { return discovery::sizeInByteStream(header.messageType); } template friend It toNetworkByteStream(const MessageHeader& header, It out) { return discovery::toNetworkByteStream(header.messageType, std::move(out)); } template static std::pair fromNetworkByteStream(It begin, const It end) { using namespace discovery; MessageHeader header; std::tie(header.messageType, begin) = Deserialize::fromNetworkByteStream(begin, end); return std::make_pair(std::move(header), std::move(begin)); } }; namespace detail { // Types that are only used in the sending/parsing of messages, not // publicly exposed. using ProtocolHeader = std::array; const ProtocolHeader kProtocolHeader = {{'_', 'l', 'i', 'n', 'k', '_', 'v', 1}}; // Must have at least kMaxMessageSize bytes available in the output stream template It encodeMessage(const MessageType messageType, const Payload& payload, It out) { using namespace std; const MessageHeader header = {messageType}; const auto messageSize = kProtocolHeader.size() + sizeInByteStream(header) + sizeInByteStream(payload); if (messageSize < kMaxMessageSize) { return toNetworkByteStream( payload, toNetworkByteStream( header, copy(begin(kProtocolHeader), end(kProtocolHeader), move(out)))); } else { throw range_error("Exceeded maximum message size"); } } } // namespace detail template It pingMessage(const Payload& payload, It out) { return detail::encodeMessage(kPing, payload, std::move(out)); } template It pongMessage(const Payload& payload, It out) { return detail::encodeMessage(kPong, payload, std::move(out)); } template std::pair parseMessageHeader(It bytesBegin, const It bytesEnd) { using ItDiff = typename std::iterator_traits::difference_type; MessageHeader header = {}; const auto protocolHeaderSize = discovery::sizeInByteStream(detail::kProtocolHeader); const auto minMessageSize = static_cast(protocolHeaderSize + sizeInByteStream(header)); // If there are enough bytes in the stream to make a header and if // the first bytes in the stream are the protocol header, then // proceed to parse the stream. if (std::distance(bytesBegin, bytesEnd) >= minMessageSize && std::equal( begin(detail::kProtocolHeader), end(detail::kProtocolHeader), bytesBegin)) { std::tie(header, bytesBegin) = MessageHeader::fromNetworkByteStream(bytesBegin + protocolHeaderSize, bytesEnd); } return std::make_pair(std::move(header), std::move(bytesBegin)); } } // namespace v1 } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/PingResponder.hpp0000644000175000017500000001230512765602651023101 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include #include #include #include #include namespace ableton { namespace link { template class PingResponder { public: PingResponder(asio::ip::address_v4 address, SessionId sessionId, GhostXForm ghostXForm, util::Injected io, Clock clock, util::Injected log) : mIo(std::move(io)) , mpImpl(std::make_shared(*mIo, std::move(address), std::move(sessionId), std::move(ghostXForm), std::move(clock), std::move(log))) { mpImpl->listen(); } PingResponder(const PingResponder&) = delete; PingResponder(PingResponder&&) = delete; ~PingResponder() { // post the release of the impl object into the io service so that // it happens in the same thread as its handlers auto pImpl = mpImpl; mIo->post([pImpl]() mutable { pImpl.reset(); }); } void updateNodeState(const SessionId& sessionId, const GhostXForm& xform) { auto pImpl = mpImpl; mIo->post([pImpl, sessionId, xform] { pImpl->mSessionId = std::move(sessionId); pImpl->mGhostXForm = std::move(xform); }); } asio::ip::udp::endpoint endpoint() const { return mpImpl->mSocket.endpoint(); } asio::ip::address address() const { return endpoint().address(); } Socket socket() const { return mpImpl->mSocket; } private: struct Impl : std::enable_shared_from_this { Impl(typename util::Injected::type& io, asio::ip::address_v4 address, SessionId sessionId, GhostXForm ghostXForm, Clock clock, util::Injected log) : mSessionId(std::move(sessionId)) , mGhostXForm(std::move(ghostXForm)) , mClock(std::move(clock)) , mLog(std::move(log)) , mSocket(io) { configureUnicastSocket(mSocket, address); } void listen() { mSocket.receive(util::makeAsyncSafe(this->shared_from_this())); } // Operator to handle incoming messages on the interface template void operator()(const asio::ip::udp::endpoint& from, const It begin, const It end) { using namespace discovery; // Decode Ping Message const auto result = link::v1::parseMessageHeader(begin, end); const auto& header = result.first; const auto payloadBegin = result.second; // Check Payload size const auto payloadSize = static_cast(std::distance(payloadBegin, end)); const auto maxPayloadSize = sizeInByteStream(makePayload(HostTime{}, PrevGHostTime{})); if (header.messageType == v1::kPing && payloadSize <= maxPayloadSize) { debug(*mLog) << "Received ping message from " << from; try { reply(std::move(payloadBegin), std::move(end), from); } catch (const std::runtime_error& err) { info(*mLog) << "Failed to send pong to " << from << ". Reason: " << err.what(); } } else { info(*mLog) << "Received invalid Message from " << from << "."; } listen(); } template void reply(It begin, It end, const asio::ip::udp::endpoint& to) { using namespace discovery; // Encode Pong Message const auto id = SessionMembership{mSessionId}; const auto currentGt = GHostTime{mGhostXForm.hostToGhost(mClock.micros())}; const auto pongPayload = makePayload(id, currentGt); v1::MessageBuffer pongBuffer; const auto pongMsgBegin = std::begin(pongBuffer); auto pongMsgEnd = v1::pongMessage(pongPayload, pongMsgBegin); // Append ping payload to pong message. pongMsgEnd = std::copy(begin, end, pongMsgEnd); const auto numBytes = static_cast(std::distance(pongMsgBegin, pongMsgEnd)); mSocket.send(pongBuffer.data(), numBytes, to); } SessionId mSessionId; GhostXForm mGhostXForm; Clock mClock; util::Injected mLog; Socket mSocket; }; util::Injected mIo; std::shared_ptr mpImpl; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/MeasurementEndpointV4.hpp0000644000175000017500000000437312765602651024530 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace link { struct MeasurementEndpointV4 { enum { key = 'mep4' }; // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const MeasurementEndpointV4 mep) { return discovery::sizeInByteStream( static_cast(mep.ep.address().to_v4().to_ulong())) + discovery::sizeInByteStream(mep.ep.port()); } template friend It toNetworkByteStream(const MeasurementEndpointV4 mep, It out) { return discovery::toNetworkByteStream( mep.ep.port(), discovery::toNetworkByteStream( static_cast(mep.ep.address().to_v4().to_ulong()), std::move(out))); } template static std::pair fromNetworkByteStream(It begin, It end) { using namespace std; auto addrRes = discovery::Deserialize::fromNetworkByteStream(move(begin), end); auto portRes = discovery::Deserialize::fromNetworkByteStream( move(addrRes.second), end); return make_pair(MeasurementEndpointV4{{asio::ip::address_v4{move(addrRes.first)}, move(portRes.first)}}, move(portRes.second)); } asio::ip::udp::endpoint ep; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Gateway.hpp0000644000175000017500000000553712765602651021734 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace link { template class Gateway { public: Gateway(util::Injected io, asio::ip::address_v4 addr, util::Injected observer, NodeState nodeState, GhostXForm ghostXForm, Clock clock) // TODO: Measurement should have an IoContext injected : mIo(std::move(io)), mMeasurement(addr, nodeState.sessionId, std::move(ghostXForm), std::move(clock), util::injectVal(channel(mIo->log(), "gateway@" + addr.to_string()))), mPeerGateway(discovery::makeIpV4Gateway(util::injectRef(*mIo), std::move(addr), std::move(observer), PeerState{std::move(nodeState), mMeasurement.endpoint()})) { } Gateway(const Gateway& rhs) = delete; Gateway& operator=(const Gateway& rhs) = delete; Gateway(Gateway&& rhs) : mIo(std::move(rhs.mIo)) , mMeasurement(std::move(rhs.mMeasurement)) , mPeerGateway(std::move(rhs.mPeerGateway)) { } Gateway& operator=(Gateway&& rhs) { mIo = std::move(rhs.mIo); mMeasurement = std::move(rhs.mMeasurement); mPeerGateway = std::move(rhs.mPeerGateway); return *this; } void updateNodeState(std::pair state) { mMeasurement.updateNodeState(state.first.sessionId, state.second); mPeerGateway.updateState(PeerState{std::move(state.first), mMeasurement.endpoint()}); } template void measurePeer(const PeerState& peer, Handler handler) { mMeasurement.measurePeer(peer, std::move(handler)); } private: util::Injected mIo; MeasurementService::type::Log> mMeasurement; discovery::IpV4Gateway::type&> mPeerGateway; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/PeerState.hpp0000644000175000017500000000452712765602651022225 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace link { // A state type for peers. PeerState stores the normal NodeState plus // additional information (the remote endpoint at which to find its // ping/pong measurement server). struct PeerState { using IdType = NodeId; IdType ident() const { return nodeState.ident(); } SessionId sessionId() const { return nodeState.sessionId; } Timeline timeline() const { return nodeState.timeline; } friend bool operator==(const PeerState& lhs, const PeerState& rhs) { return lhs.nodeState == rhs.nodeState && lhs.endpoint == rhs.endpoint; } friend auto toPayload(const PeerState& state) -> decltype(std::declval() + discovery::makePayload(MeasurementEndpointV4{{}})) { return toPayload(state.nodeState) + discovery::makePayload(MeasurementEndpointV4{state.endpoint}); } template static PeerState fromPayload(NodeId id, It begin, It end) { using namespace std; auto peerState = PeerState{NodeState::fromPayload(move(id), begin, end), {}}; discovery::parsePayload(move(begin), move(end), [&peerState](MeasurementEndpointV4 me4) { peerState.endpoint = move(me4.ep); }); return peerState; } NodeState nodeState; asio::ip::udp::endpoint endpoint; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/NodeId.hpp0000644000175000017500000000434612765602651021472 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include namespace ableton { namespace link { using NodeIdArray = std::array; struct NodeId : NodeIdArray { NodeId() = default; NodeId(NodeIdArray rhs) : NodeIdArray(std::move(rhs)) { } static NodeId random() { using namespace std; random_device rd; mt19937 gen(rd()); // uint8_t not standardized for this type - use unsigned uniform_int_distribution dist(33, 126); // printable ascii chars NodeId nodeId; generate( nodeId.begin(), nodeId.end(), [&] { return static_cast(dist(gen)); }); return nodeId; } friend std::ostream& operator<<(std::ostream& stream, const NodeId& id) { return stream << std::string{id.cbegin(), id.cend()}; } template friend It toNetworkByteStream(const NodeId& nodeId, It out) { return discovery::toNetworkByteStream(nodeId, std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { using namespace std; auto result = discovery::Deserialize::fromNetworkByteStream(move(begin), move(end)); return make_pair(NodeId(move(result.first)), move(result.second)); } }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/ClientSessionTimelines.hpp0000644000175000017500000001153512765602651024762 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace link { // Clamp the tempo of the given timeline to the valid Link range inline Timeline clampTempo(const Timeline timeline) { const double kMinBpm = 20.0; const double kMaxBpm = 999.0; return {Tempo{(std::min)((std::max)(timeline.tempo.bpm(), kMinBpm), kMaxBpm)}, timeline.beatOrigin, timeline.timeOrigin}; } // Given an existing client timeline, a session timeline, and the // global host transform of the session, return a new version of the client // timeline. The resulting new client timeline is continuous with the // previous timeline so that curClient.toBeats(atTime) == // result.toBeats(atTime). inline Timeline updateClientTimelineFromSession(const Timeline curClient, const Timeline session, const std::chrono::microseconds atTime, const GhostXForm xform) { // An intermediate timeline representing the continuation of the // existing client timeline with the tempo from the session timeline. const auto tempTl = Timeline{session.tempo, curClient.toBeats(atTime), atTime}; // The host time corresponding to beat 0 on the session // timeline. Beat 0 on the session timeline is important because it // serves as the origin of the quantization grid for all participants. const auto hostBeatZero = xform.ghostToHost(session.fromBeats(Beats{INT64_C(0)})); // The new client timeline becomes the result of sliding the // intermediate timeline back so that it's anchor corresponds to // beat zero on the session timeline. The result preserves the // magnitude of beats on the client timeline while encoding the // quantization reference point in the time and beatOrigins. return {tempTl.tempo, tempTl.toBeats(hostBeatZero), hostBeatZero}; } inline Timeline updateSessionTimelineFromClient(const Timeline curSession, const Timeline client, const std::chrono::microseconds atTime, const GhostXForm xform) { // The client timeline was constructed so that it's timeOrigin // corresponds to beat 0 on the session timeline. const auto ghostBeat0 = xform.hostToGhost(client.timeOrigin); const auto zero = Beats{INT64_C(0)}; // If beat 0 was not shifted and there is not a new tempo, an update // of the session timeline is not required. Don't create an // equivalent timeline with different anchor points if not needed as // this will trigger other unnecessary changes. if (curSession.toBeats(ghostBeat0) == zero && client.tempo == curSession.tempo) { return curSession; } else { // An intermediate timeline representing the new tempo, the // effective time, and a possibly adjusted origin. const auto tempTl = Timeline{client.tempo, zero, ghostBeat0}; // The final session timeline must have the beat corresponding to // atTime on the old session timeline as its beatOrigin because this is // used for prioritization of timelines among peers - we can't let a // modification applied by the client artificially increase or // reduce the timeline's priority in the session. The new beat // origin should be as close as possible to lining up with atTime, // but we must also make sure that it's > curSession.beatOrigin // because otherwise it will get ignored. const auto newBeatOrigin = (std::max)(curSession.toBeats(xform.hostToGhost(atTime)), curSession.beatOrigin + Beats{INT64_C(1)}); return {client.tempo, newBeatOrigin, tempTl.fromBeats(newBeatOrigin)}; } } // Shift timeline so result.toBeats(t) == client.toBeats(t) + // shift. This takes into account the fact that the timeOrigin // corresponds to beat 0 on the session timeline. Using this function // and then setting the session timeline with the result will change // the phase of the session by the given shift amount. inline Timeline shiftClientTimeline(Timeline client, const Beats shift) { const auto timeDelta = client.fromBeats(shift) - client.fromBeats(Beats{INT64_C(0)}); client.timeOrigin = client.timeOrigin - timeDelta; return client; } } // link } // ableton link-Link-1.0.0/include/ableton/link/SessionId.hpp0000644000175000017500000000360112765602651022221 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace link { // SessionIds occupy the same value space as NodeIds and are // identified by their founding node. using SessionId = NodeId; // A payload entry indicating membership in a particular session struct SessionMembership { enum { key = 'sess' }; // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const SessionMembership& sm) { return discovery::sizeInByteStream(sm.sessionId); } template friend It toNetworkByteStream(const SessionMembership& sm, It out) { return discovery::toNetworkByteStream(sm.sessionId, std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { using namespace std; auto idRes = SessionId::fromNetworkByteStream(move(begin), move(end)); return make_pair(SessionMembership{move(idRes.first)}, move(idRes.second)); } SessionId sessionId; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/HostTimeFilter.hpp0000644000175000017500000000403312765602651023223 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace link { template class HostTimeFilter { static const std::size_t kNumPoints = 512; using Points = std::vector>; using PointIt = typename Points::iterator; public: HostTimeFilter() : mIndex(0) { mPoints.reserve(kNumPoints); } ~HostTimeFilter() = default; void reset() { mIndex = 0; mPoints.clear(); } std::chrono::microseconds sampleTimeToHostTime(const double sampleTime) { const auto micros = static_cast(mHostTimeSampler.micros().count()); const auto point = std::make_pair(sampleTime, micros); if (mPoints.size() < kNumPoints) { mPoints.push_back(point); } else { mPoints[mIndex] = point; } mIndex = (mIndex + 1) % kNumPoints; const auto result = linearRegression(mPoints.begin(), mPoints.end()); const auto hostTime = (result.first * sampleTime) + result.second; return std::chrono::microseconds(llround(hostTime)); } private: std::size_t mIndex; Points mPoints; T mHostTimeSampler; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Beats.hpp0000644000175000017500000000517312765602651021365 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include namespace ableton { namespace link { struct Beats : std::tuple { Beats() = default; explicit Beats(const double beats) : std::tuple(std::llround(beats * 1e6)) { } explicit Beats(const std::int64_t microBeats) : std::tuple(microBeats) { } double floating() const { return microBeats() / 1e6; } std::int64_t microBeats() const { return std::get<0>(*this); } Beats operator-() const { return Beats{-microBeats()}; } friend Beats abs(const Beats b) { return Beats{std::abs(b.microBeats())}; } friend Beats operator+(const Beats lhs, const Beats rhs) { return Beats{lhs.microBeats() + rhs.microBeats()}; } friend Beats operator-(const Beats lhs, const Beats rhs) { return Beats{lhs.microBeats() - rhs.microBeats()}; } friend Beats operator%(const Beats lhs, const Beats rhs) { return rhs == Beats{0.} ? Beats{0.} : Beats{lhs.microBeats() % rhs.microBeats()}; } // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const Beats beats) { return discovery::sizeInByteStream(beats.microBeats()); } template friend It toNetworkByteStream(const Beats beats, It out) { return discovery::toNetworkByteStream(beats.microBeats(), std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { auto result = discovery::Deserialize::fromNetworkByteStream( std::move(begin), std::move(end)); return std::make_pair(Beats{result.first}, std::move(result.second)); } }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Measurement.hpp0000644000175000017500000002001012765602651022577 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include #include #include #include #include namespace ableton { namespace link { template struct Measurement { using Point = std::pair; using Callback = std::function)>; using Micros = std::chrono::microseconds; using Timer = typename IoService::Timer; static const std::size_t kNumberDataPoints = 100; static const std::size_t kNumberMeasurements = 5; Measurement() = default; Measurement(const PeerState& state, Callback callback, asio::ip::address_v4 address, Clock clock, util::Injected log) : mpIo(new IoService{}) , mpImpl(std::make_shared(*mpIo, std::move(state), std::move(callback), std::move(address), std::move(clock), std::move(log))) { mpImpl->listen(); } Measurement(Measurement&& rhs) : mpIo(std::move(rhs.mpIo)) , mpImpl(std::move(rhs.mpImpl)) { } ~Measurement() { postImplDestruction(); } Measurement& operator=(Measurement&& rhs) { postImplDestruction(); mpIo = std::move(rhs.mpIo); mpImpl = std::move(rhs.mpImpl); return *this; } void postImplDestruction() { // Post destruction of the impl object into the io thread if valid if (mpIo) { mpIo->post(ImplDeleter{*this}); } } struct Impl : std::enable_shared_from_this { Impl(IoService& io, const PeerState& state, Callback callback, asio::ip::address_v4 address, Clock clock, util::Injected log) : mpSocket(std::make_shared(io)) , mSessionId(state.nodeState.sessionId) , mEndpoint(state.endpoint) , mCallback(std::move(callback)) , mClock(std::move(clock)) , mTimer(util::injectVal(io.makeTimer())) , mMeasurementsStarted(0) , mLog(std::move(log)) , mSuccess(false) { configureUnicastSocket(*mpSocket, address); const auto ht = HostTime{mClock.micros()}; sendPing(mEndpoint, discovery::makePayload(ht)); resetTimer(); } void resetTimer() { mTimer->cancel(); mTimer->expires_from_now(std::chrono::milliseconds(50)); mTimer->async_wait([this](const typename Timer::ErrorCode e) { if (!e) { if (mMeasurementsStarted < kNumberMeasurements) { const auto ht = HostTime{mClock.micros()}; sendPing(mEndpoint, discovery::makePayload(ht)); ++mMeasurementsStarted; resetTimer(); } else { fail(); } } }); } void listen() { mpSocket->receive(util::makeAsyncSafe(this->shared_from_this())); } // Operator to handle incoming messages on the interface template void operator()( const asio::ip::udp::endpoint& from, const It messageBegin, const It messageEnd) { using namespace std; const auto result = v1::parseMessageHeader(messageBegin, messageEnd); const auto& header = result.first; const auto payloadBegin = result.second; if (header.messageType == v1::kPong) { debug(*mLog) << "Received Pong message from " << from; // parse for all entries SessionId sessionId{}; std::chrono::microseconds ghostTime{0}; std::chrono::microseconds prevGHostTime{0}; std::chrono::microseconds prevHostTime{0}; try { discovery::parsePayload( payloadBegin, messageEnd, [&sessionId](const SessionMembership& sms) { sessionId = sms.sessionId; }, [&ghostTime](GHostTime gt) { ghostTime = std::move(gt.time); }, [&prevGHostTime](PrevGHostTime gt) { prevGHostTime = std::move(gt.time); }, [&prevHostTime](HostTime ht) { prevHostTime = std::move(ht.time); }); } catch (const std::runtime_error& err) { warning(*mLog) << "Failed parsing payload, caught exception: " << err.what(); listen(); return; } if (mSessionId == sessionId) { const auto hostTime = mClock.micros(); const auto payload = discovery::makePayload(HostTime{hostTime}, PrevGHostTime{ghostTime}); sendPing(from, payload); listen(); if (prevGHostTime != Micros{0}) { mData.push_back( std::make_pair(static_cast((hostTime + prevHostTime).count()) * 0.5, static_cast(ghostTime.count()))); mData.push_back(std::make_pair(static_cast(prevHostTime.count()), static_cast((ghostTime + prevGHostTime).count()) * 0.5)); } if (mData.size() > kNumberDataPoints) { finish(); } else { resetTimer(); } } else { fail(); } } else { debug(*mLog) << "Received invalid message from " << from; listen(); } } template void sendPing(asio::ip::udp::endpoint to, const Payload& payload) { v1::MessageBuffer buffer; const auto msgBegin = std::begin(buffer); const auto msgEnd = v1::pingMessage(payload, msgBegin); const auto numBytes = static_cast(std::distance(msgBegin, msgEnd)); try { mpSocket->send(buffer.data(), numBytes, to); } catch (const std::runtime_error& err) { info(*mLog) << "Failed to send Ping to " << to.address().to_string() << ": " << err.what(); } } void finish() { mTimer->cancel(); mCallback(std::move(mData)); mData = {}; mSuccess = true; debug(*mLog) << "Measuring " << mEndpoint << " done."; } void fail() { mCallback(std::vector{}); mData = {}; debug(*mLog) << "Measuring " << mEndpoint << " failed."; } std::shared_ptr mpSocket; SessionId mSessionId; asio::ip::udp::endpoint mEndpoint; std::vector> mData; Callback mCallback; Clock mClock; util::Injected mTimer; std::size_t mMeasurementsStarted; util::Injected mLog; bool mSuccess; }; struct ImplDeleter { ImplDeleter(Measurement& measurement) : mpImpl(std::move(measurement.mpImpl)) { } void operator()() { // Notify callback that the measurement has failed if it did // not succeed before destruction if (!mpImpl->mSuccess) { mpImpl->fail(); } mpImpl.reset(); } std::shared_ptr mpImpl; }; std::unique_ptr mpIo; std::shared_ptr mpImpl; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Controller.hpp0000644000175000017500000003240012765602651022443 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include #include #include namespace ableton { namespace link { namespace detail { template GhostXForm initXForm(const Clock& clock) { // Make the current time map to a ghost time of 0 with ghost time // increasing at the same rate as clock time return {1.0, -clock.micros()}; } // The timespan in which local modifications to the timeline will be // preferred over any modifications coming from the network. const auto kLocalModGracePeriod = std::chrono::seconds(1); } // namespace detail // function types corresponding to the Controller callback type params using PeerCountCallback = std::function; using TempoCallback = std::function; // The main Link controller template class Controller { public: using Ticks = typename Clock::Ticks; Controller(Tempo tempo, PeerCountCallback peerCallback, TempoCallback tempoCallback, Clock clock, util::Injected io) : mTempoCallback(std::move(tempoCallback)) , mClock(std::move(clock)) , mNodeId(NodeId::random()) , mSessionId(mNodeId) , mGhostXForm(detail::initXForm(mClock)) , mSessionTimeline(clampTempo({tempo, Beats{0.}, std::chrono::microseconds{0}})) , mClientTimeline({mSessionTimeline.tempo, Beats{0.}, mGhostXForm.ghostToHost(std::chrono::microseconds{0})}) , mRtClientTimeline(mClientTimeline) , mRtClientTimelineTimestamp(0) , mSessionPeerCounter(*this, std::move(peerCallback)) , mEnabled(false) , mIo(std::move(io)) , mRealtimeIo(util::injectRef(*mIo)) , mPeers(util::injectRef(*mIo), std::ref(mSessionPeerCounter), SessionTimelineCallback{*this}) , mSessions({mSessionId, mSessionTimeline, {mGhostXForm, mClock.micros()}}, util::injectRef(mPeers), MeasurePeer{*this}, JoinSessionCallback{*this}, util::injectRef(*mIo), mClock) , mDiscovery( std::make_pair(NodeState{mNodeId, mSessionId, mSessionTimeline}, mGhostXForm), GatewayFactory{*this}, util::injectVal(mIo->clone(UdpSendExceptionHandler{*this}))) { } Controller(const Controller&) = delete; Controller(Controller&&) = delete; Controller& operator=(const Controller&) = delete; Controller& operator=(Controller&&) = delete; void enable(const bool bEnable) { const bool bWasEnabled = mEnabled.exchange(bEnable); if (bWasEnabled != bEnable) { mRealtimeIo.async([this, bEnable] { if (bEnable) { // Always reset when first enabling to avoid hijacking // tempo in existing sessions resetState(); } mDiscovery.enable(bEnable); }); } } bool isEnabled() const { return mEnabled; } std::size_t numPeers() const { return mSessionPeerCounter.mSessionPeerCount; } // Get the current Link timeline. Thread-safe but may block, so // it cannot be used from audio thread. Timeline timeline() const { std::lock_guard lock(mClientTimelineGuard); return mClientTimeline; } // Set the timeline to be used, starting at the given // time. Thread-safe but may block, so it cannot be used from audio thread. void setTimeline(Timeline newTimeline, const std::chrono::microseconds atTime) { newTimeline = clampTempo(newTimeline); { std::lock_guard lock(mClientTimelineGuard); mClientTimeline = newTimeline; } mIo->async([this, newTimeline, atTime] { handleTimelineFromClient(updateSessionTimelineFromClient( mSessionTimeline, newTimeline, atTime, mGhostXForm)); }); } // Non-blocking timeline access for a realtime context. NOT // thread-safe. Must not be called from multiple threads // concurrently and must not be called concurrently with setTimelineRtSafe. Timeline timelineRtSafe() const { // Respect the session timing guard but don't block on it. If we // can't access it because it's being modified we fall back to our // cached version of the timeline. const auto now = mClock.micros(); if (now - mRtClientTimelineTimestamp > detail::kLocalModGracePeriod && mSessionTimingGuard.try_lock()) { const auto clientTimeline = updateClientTimelineFromSession( mRtClientTimeline, mSessionTimeline, now, mGhostXForm); mSessionTimingGuard.unlock(); if (clientTimeline != mRtClientTimeline) { mRtClientTimeline = clientTimeline; } } return mRtClientTimeline; } // should only be called from the audio thread void setTimelineRtSafe(Timeline newTimeline, const std::chrono::microseconds atTime) { newTimeline = clampTempo(newTimeline); // Cache the new timeline for serving back to the client mRtClientTimeline = newTimeline; mRtClientTimelineTimestamp = mClock.micros(); // Update the session timeline from the new client timeline mRealtimeIo.async([this, newTimeline, atTime] { // Synchronize with the non-rt version of the client timeline { std::lock_guard lock(mClientTimelineGuard); mClientTimeline = newTimeline; } handleTimelineFromClient(updateSessionTimelineFromClient( mSessionTimeline, newTimeline, atTime, mGhostXForm)); }); } private: void updateSessionTiming(const Timeline newTimeline, const GhostXForm newXForm) { const auto oldTimeline = mSessionTimeline; const auto oldXForm = mGhostXForm; if (oldTimeline != newTimeline || oldXForm != newXForm) { { std::lock_guard lock(mSessionTimingGuard); mSessionTimeline = newTimeline; mGhostXForm = newXForm; } // Update the client timeline based on the new session timing data { std::lock_guard lock(mClientTimelineGuard); mClientTimeline = updateClientTimelineFromSession( mClientTimeline, mSessionTimeline, mClock.micros(), mGhostXForm); } // Push the change to the discovery service mDiscovery.updateNodeState( std::make_pair(NodeState{mNodeId, mSessionId, newTimeline}, newXForm)); if (oldTimeline.tempo != newTimeline.tempo) { mTempoCallback(newTimeline.tempo); } } } void handleTimelineFromClient(Timeline tl) { mSessions.resetTimeline(tl); mPeers.setSessionTimeline(mSessionId, tl); updateSessionTiming(std::move(tl), mGhostXForm); } void handleTimelineFromSession(SessionId id, Timeline timeline) { debug(mIo->log()) << "Received timeline with tempo: " << timeline.tempo.bpm() << " for session: " << id; updateSessionTiming( mSessions.sawSessionTimeline(std::move(id), std::move(timeline)), mGhostXForm); } void joinSession(const Session& session) { const bool sessionIdChanged = mSessionId != session.sessionId; mSessionId = session.sessionId; updateSessionTiming(session.timeline, session.measurement.xform); if (sessionIdChanged) { debug(mIo->log()) << "Joining session " << session.sessionId << " with tempo " << session.timeline.tempo.bpm(); mSessionPeerCounter(); } } void resetState() { mNodeId = NodeId::random(); mSessionId = mNodeId; const auto xform = detail::initXForm(mClock); const auto hostTime = -xform.intercept; // When creating the new timeline, make it continuous by finding // the beat on the old session timeline corresponding to the // current host time and mapping it to the new ghost time // representation of the current host time. const auto newTl = Timeline{mSessionTimeline.tempo, mSessionTimeline.toBeats(mGhostXForm.hostToGhost(hostTime)), xform.hostToGhost(hostTime)}; updateSessionTiming(newTl, xform); mSessions.resetSession({mNodeId, newTl, {xform, hostTime}}); mPeers.resetPeers(); } struct SessionTimelineCallback { void operator()(SessionId id, Timeline timeline) { mController.handleTimelineFromSession(std::move(id), std::move(timeline)); } Controller& mController; }; struct SessionPeerCounter { SessionPeerCounter(Controller& controller, PeerCountCallback callback) : mController(controller) , mCallback(std::move(callback)) , mSessionPeerCount(0) { } void operator()() { const auto count = mController.mPeers.uniqueSessionPeerCount(mController.mSessionId); const auto oldCount = mSessionPeerCount.exchange(count); if (oldCount != count) { if (count == 0) { // When the count goes down to zero, completely reset the // state, effectively founding a new session mController.resetState(); } mCallback(count); } } Controller& mController; PeerCountCallback mCallback; std::atomic mSessionPeerCount; }; struct MeasurePeer { template void operator()(Peer peer, Handler handler) { using It = typename Discovery::ServicePeerGateways::GatewayMap::iterator; using ValueType = typename Discovery::ServicePeerGateways::GatewayMap::value_type; mController.mDiscovery.withGatewaysAsync([peer, handler](It begin, const It end) { const auto addr = peer.second; const auto it = std::find_if( begin, end, [&addr](const ValueType& vt) { return vt.first == addr; }); if (it != end) { it->second->measurePeer(std::move(peer.first), std::move(handler)); } else { // invoke the handler with an empty result if we couldn't // find the peer's gateway handler(GhostXForm{}); } }); } Controller& mController; }; struct JoinSessionCallback { void operator()(Session session) { mController.joinSession(std::move(session)); } Controller& mController; }; using IoType = typename util::Injected::type; using ControllerPeers = Peers, SessionTimelineCallback>; using ControllerGateway = Gateway; using GatewayPtr = std::shared_ptr; struct GatewayFactory { GatewayPtr operator()(std::pair state, util::Injected io, const asio::ip::address& addr) { if (addr.is_v4()) { return GatewayPtr{new ControllerGateway{std::move(io), addr.to_v4(), util::injectVal(makeGatewayObserver(mController.mPeers, addr)), std::move(state.first), std::move(state.second), mController.mClock}}; } else { throw std::runtime_error("Could not create peer gateway on non-ipV4 address"); } } Controller& mController; }; struct UdpSendExceptionHandler { using Exception = discovery::UdpSendException; void operator()(const Exception& exception) { mController.mDiscovery.repairGateway(exception.interfaceAddr); } Controller& mController; }; TempoCallback mTempoCallback; Clock mClock; NodeId mNodeId; SessionId mSessionId; // Mutex that controls access to mGhostXForm and mSessionTimeline mutable std::mutex mSessionTimingGuard; GhostXForm mGhostXForm; Timeline mSessionTimeline; mutable std::mutex mClientTimelineGuard; Timeline mClientTimeline; mutable Timeline mRtClientTimeline; std::chrono::microseconds mRtClientTimelineTimestamp; SessionPeerCounter mSessionPeerCounter; std::atomic mEnabled; util::Injected mIo; // A realtime facade over the provided IoContext. This should only // be used by realtime code, non-realtime code should use mIo. typename IoType::template RealTimeContext mRealtimeIo; ControllerPeers mPeers; using ControllerSessions = Sessions::type&, Clock>; ControllerSessions mSessions; using Discovery = discovery::Service, GatewayFactory, IoContext>; Discovery mDiscovery; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/NodeState.hpp0000644000175000017500000000403612765602651022212 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include namespace ableton { namespace link { struct NodeState { using Payload = decltype(discovery::makePayload(Timeline{}, SessionMembership{})); NodeId ident() const { return nodeId; } friend bool operator==(const NodeState& lhs, const NodeState& rhs) { return std::tie(lhs.nodeId, lhs.sessionId, lhs.timeline) == std::tie(rhs.nodeId, rhs.sessionId, rhs.timeline); } friend Payload toPayload(const NodeState& state) { return discovery::makePayload(state.timeline, SessionMembership{state.sessionId}); } template static NodeState fromPayload(NodeId id, It begin, It end) { using namespace std; auto state = NodeState{move(id), {}, {}}; discovery::parsePayload(move(begin), move(end), [&state](Timeline tl) { state.timeline = move(tl); }, [&state](SessionMembership sm) { state.sessionId = move(sm.sessionId); }); return state; } NodeId nodeId; SessionId sessionId; Timeline timeline; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Timeline.hpp0000644000175000017500000000557612765602651022104 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include namespace ableton { namespace link { // A tuple of (tempo, beats, time), with integral units // based on microseconds. This type establishes a bijection between // beats and wall time, given a valid tempo. It also serves as a // payload entry. struct Timeline { enum { key = 'tmln' }; Beats toBeats(const std::chrono::microseconds time) const { return beatOrigin + tempo.microsToBeats(time - timeOrigin); } std::chrono::microseconds fromBeats(const Beats beats) const { return timeOrigin + tempo.beatsToMicros(beats - beatOrigin); } friend bool operator==(const Timeline& lhs, const Timeline& rhs) { return std::tie(lhs.tempo, lhs.beatOrigin, lhs.timeOrigin) == std::tie(rhs.tempo, rhs.beatOrigin, rhs.timeOrigin); } friend bool operator!=(const Timeline& lhs, const Timeline& rhs) { return !(lhs == rhs); } // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const Timeline& tl) { return discovery::sizeInByteStream(std::tie(tl.tempo, tl.beatOrigin, tl.timeOrigin)); } template friend It toNetworkByteStream(const Timeline& tl, It out) { return discovery::toNetworkByteStream( std::tie(tl.tempo, tl.beatOrigin, tl.timeOrigin), std::move(out)); } template static std::pair fromNetworkByteStream(It begin, It end) { using namespace std; using namespace discovery; Timeline timeline; auto result = Deserialize>::fromNetworkByteStream( move(begin), move(end)); tie(timeline.tempo, timeline.beatOrigin, timeline.timeOrigin) = move(result.first); return make_pair(move(timeline), move(result.second)); } Tempo tempo; Beats beatOrigin; std::chrono::microseconds timeOrigin; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/GhostXForm.hpp0000644000175000017500000000313212765602651022360 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace link { using std::chrono::microseconds; struct GhostXForm { microseconds hostToGhost(const microseconds hostTime) const { return microseconds{llround(slope * hostTime.count())} + intercept; } microseconds ghostToHost(const microseconds ghostTime) const { return microseconds{llround((ghostTime - intercept).count() / slope)}; } friend bool operator==(const GhostXForm lhs, const GhostXForm rhs) { return lhs.slope == rhs.slope && lhs.intercept == rhs.intercept; } friend bool operator!=(const GhostXForm lhs, const GhostXForm rhs) { return !(lhs == rhs); } double slope; microseconds intercept; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Phase.hpp0000644000175000017500000000764112765602651021371 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace link { // Returns a value in the range [0,quantum) corresponding to beats % // quantum except that negative beat values are handled correctly. // If the given quantum is zero, returns zero. inline Beats phase(const Beats beats, const Beats quantum) { if (quantum == Beats{INT64_C(0)}) { return Beats{INT64_C(0)}; } else { // Handle negative beat values by doing the computation relative to an // origin that is on the nearest quantum boundary less than -(abs(x)) const auto quantumMicros = quantum.microBeats(); const auto quantumBins = (llabs(beats.microBeats()) + quantumMicros) / quantumMicros; const std::int64_t quantumBeats{quantumBins * quantumMicros}; return (beats + Beats{quantumBeats}) % quantum; } } // Return the least value greater than x that matches the phase of // target with respect to the given quantum. If the given quantum // quantum is 0, x is returned. inline Beats nextPhaseMatch(const Beats x, const Beats target, const Beats quantum) { const auto desiredPhase = phase(target, quantum); const auto xPhase = phase(x, quantum); const auto phaseDiff = (desiredPhase - xPhase + quantum) % quantum; return x + phaseDiff; } // Return the closest value to x that matches the phase of the target // with respect to the given quantum. The result deviates from x by at // most quantum/2, but may be less than x. inline Beats closestPhaseMatch(const Beats x, const Beats target, const Beats quantum) { return nextPhaseMatch(x - Beats{0.5 * quantum.floating()}, target, quantum); } // Interprets the given timeline as encoding a quantum boundary at its // origin. Given such a timeline, returns a phase-encoded beat value // relative to the given quantum that corresponds to the given // time. The phase of the resulting beat value can be calculated with // phase(beats, quantum). The result will deviate by up to +- // (quantum/2) beats compared to the result of tl.toBeats(time). inline Beats toPhaseEncodedBeats( const Timeline& tl, const std::chrono::microseconds time, const Beats quantum) { const auto beat = tl.toBeats(time); return closestPhaseMatch(beat, beat - tl.beatOrigin, quantum); } // The inverse of toPhaseEncodedBeats. Given a phase encoded beat // value from the given timeline and quantum, find the time value that // it maps to. inline std::chrono::microseconds fromPhaseEncodedBeats( const Timeline& tl, const Beats beat, const Beats quantum) { const auto fromOrigin = beat - tl.beatOrigin; const auto originOffset = fromOrigin - phase(fromOrigin, quantum); // invert the phase calculation so that it always rounds up in the // middle instead of down like closestPhaseMatch. Otherwise we'll // end up rounding down twice when a value is at phase quantum/2. const auto inversePhaseOffset = closestPhaseMatch( quantum - phase(fromOrigin, quantum), quantum - phase(beat, quantum), quantum); return tl.fromBeats(tl.beatOrigin + originOffset + quantum - inversePhaseOffset); } } // link } // ableton link-Link-1.0.0/include/ableton/link/Sessions.hpp0000644000175000017500000002212612765602651022132 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace link { struct SessionMeasurement { GhostXForm xform; std::chrono::microseconds timestamp; }; struct Session { SessionId sessionId; Timeline timeline; SessionMeasurement measurement; }; template class Sessions { public: using Timer = typename util::Injected::type::Timer; Sessions(Session init, util::Injected peers, MeasurePeer measure, JoinSessionCallback join, util::Injected io, Clock clock) : mPeers(std::move(peers)) , mMeasure(std::move(measure)) , mCallback(std::move(join)) , mCurrent(std::move(init)) , mIo(std::move(io)) , mTimer(mIo->makeTimer()) , mClock(std::move(clock)) { } void resetSession(Session session) { mCurrent = std::move(session); mOtherSessions.clear(); } void resetTimeline(Timeline timeline) { mCurrent.timeline = std::move(timeline); } // Consider the observed session/timeline pair and return a possibly // new timeline that should be used going forward. Timeline sawSessionTimeline(SessionId sid, Timeline timeline) { using namespace std; if (sid == mCurrent.sessionId) { // matches our current session, update the timeline if necessary updateTimeline(mCurrent, move(timeline)); } else { auto session = Session{move(sid), move(timeline), {}}; const auto range = equal_range(begin(mOtherSessions), end(mOtherSessions), session, SessionIdComp{}); if (range.first == range.second) { // brand new session, insert it into our list of known // sessions and launch a measurement launchSessionMeasurement(session); mOtherSessions.insert(range.first, move(session)); } else { // we've seen this session before, update its timeline if necessary updateTimeline(*range.first, move(timeline)); } } return mCurrent.timeline; } private: void launchSessionMeasurement(Session& session) { using namespace std; auto peers = mPeers->sessionPeers(session.sessionId); if (!peers.empty()) { // first criteria: always prefer the founding peer const auto it = find_if(begin(peers), end(peers), [&session](const Peer& peer) { return session.sessionId == peer.first.ident(); }); // TODO: second criteria should be degree. We don't have that // represented yet so just use the first peer for now auto peer = it == end(peers) ? peers.front() : *it; // mark that a session is in progress by clearing out the // session's timestamp session.measurement.timestamp = {}; mMeasure(move(peer), MeasurementResultsHandler{*this, session.sessionId}); } } void handleSuccessfulMeasurement(const SessionId& id, GhostXForm xform) { using namespace std; debug(mIo->log()) << "Session " << id << " measurement completed with result " << "(" << xform.slope << ", " << xform.intercept.count() << ")"; auto measurement = SessionMeasurement{move(xform), mClock.micros()}; if (mCurrent.sessionId == id) { mCurrent.measurement = move(measurement); mCallback(mCurrent); } else { const auto range = equal_range( begin(mOtherSessions), end(mOtherSessions), Session{id, {}, {}}, SessionIdComp{}); if (range.first != range.second) { const auto SESSION_EPS = chrono::microseconds{500000}; // should we join this session? const auto hostTime = mClock.micros(); const auto curGhost = mCurrent.measurement.xform.hostToGhost(hostTime); const auto newGhost = measurement.xform.hostToGhost(hostTime); // update the measurement for the session entry range.first->measurement = move(measurement); // If session times too close - fall back to session id order const auto ghostDiff = newGhost - curGhost; if (ghostDiff > SESSION_EPS || (std::abs(ghostDiff.count()) < SESSION_EPS.count() && id < mCurrent.sessionId)) { // The new session wins, switch over to it auto current = mCurrent; mCurrent = move(*range.first); mOtherSessions.erase(range.first); // Put the old current session back into our list of known // sessions so that we won't re-measure it const auto it = upper_bound( begin(mOtherSessions), end(mOtherSessions), current, SessionIdComp{}); mOtherSessions.insert(it, move(current)); // And notify that we have a new session and make sure that // we remeasure it periodically. mCallback(mCurrent); scheduleRemeasurement(); } } } } void scheduleRemeasurement() { // set a timer to re-measure the active session after a period mTimer.expires_from_now(std::chrono::microseconds{30000000}); mTimer.async_wait([this](const typename Timer::ErrorCode e) { if (!e) { launchSessionMeasurement(mCurrent); scheduleRemeasurement(); } }); } void handleFailedMeasurement(const SessionId& id) { using namespace std; debug(mIo->log()) << "Session " << id << " measurement failed."; // if we failed to measure for our current session, schedule a // retry in the future. Otherwise, remove the session from our set // of known sessions (if it is seen again it will be measured as // if new). if (mCurrent.sessionId == id) { scheduleRemeasurement(); } else { const auto range = equal_range( begin(mOtherSessions), end(mOtherSessions), Session{id, {}, {}}, SessionIdComp{}); if (range.first != range.second) { mOtherSessions.erase(range.first); mPeers->forgetSession(id); } } } void updateTimeline(Session& session, Timeline timeline) { // We use beat origin magnitude to prioritize sessions. if (timeline.beatOrigin > session.timeline.beatOrigin) { debug(mIo->log()) << "Adopting peer timeline (" << timeline.tempo.bpm() << ", " << timeline.beatOrigin.floating() << ", " << timeline.timeOrigin.count() << ")"; session.timeline = std::move(timeline); } else { debug(mIo->log()) << "Rejecting peer timeline with beat origin: " << timeline.beatOrigin.floating() << ". Current timeline beat origin: " << session.timeline.beatOrigin.floating(); } } struct MeasurementResultsHandler { void operator()(GhostXForm xform) const { Sessions& sessions = mSessions; const SessionId& sessionId = mSessionId; if (xform == GhostXForm{}) { mSessions.mIo->async([&sessions, sessionId] { sessions.handleFailedMeasurement(std::move(sessionId)); }); } else { mSessions.mIo->async([&sessions, sessionId, xform] { sessions.handleSuccessfulMeasurement(std::move(sessionId), std::move(xform)); }); } } Sessions& mSessions; SessionId mSessionId; }; struct SessionIdComp { bool operator()(const Session& lhs, const Session& rhs) const { return lhs.sessionId < rhs.sessionId; } }; using Peer = typename util::Injected::type::Peer; util::Injected mPeers; MeasurePeer mMeasure; JoinSessionCallback mCallback; Session mCurrent; util::Injected mIo; Timer mTimer; Clock mClock; std::vector mOtherSessions; // sorted/unique by session id }; template Sessions makeSessions( Session init, util::Injected peers, MeasurePeer measure, JoinSessionCallback join, util::Injected io, Clock clock) { using namespace std; return {move(init), move(peers), move(measure), move(join), move(io), move(clock)}; } } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Kalman.hpp0000644000175000017500000000753512765602651021536 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #if LINK_PLATFORM_WINDOWS // Windows.h (or more specifically, minwindef.h) define the max(a, b) macro // which conflicts with the symbol provided by std::numeric_limits. #ifdef max #undef max #endif #endif namespace ableton { namespace link { template struct Kalman { Kalman() : mValue(0) , mGain(0) , mVVariance(1) , mWVariance(1) , mCoVariance(1) , mVarianceLength(n) , mCounter(mVarianceLength) { } double getValue() { return mValue; } double calculateVVariance() { auto vVar = 0.; auto meanOfDiffs = 0.; for (size_t k = 0; k < (mVarianceLength); k++) { meanOfDiffs += (mMeasuredValues[k] - mFilterValues[k]); } meanOfDiffs /= (mVarianceLength); for (size_t i = 0; i < (mVarianceLength); i++) { vVar += (pow(mMeasuredValues[i] - mFilterValues[i] - meanOfDiffs, 2.0)); } vVar /= (mVarianceLength - 1); return vVar; } double calculateWVariance() { auto wVar = 0.; auto meanOfDiffs = 0.; for (size_t k = 0; k < (mVarianceLength); k++) { meanOfDiffs += (mFilterValues[(mCounter - k - 1) % mVarianceLength] - mFilterValues[(mCounter - k - 2) % mVarianceLength]); } meanOfDiffs /= (mVarianceLength); for (size_t i = 0; i < (mVarianceLength); i++) { wVar += (pow(mFilterValues[(mCounter - i - 1) % mVarianceLength] - mFilterValues[(mCounter - i - 2) % mVarianceLength] - meanOfDiffs, 2.0)); } wVar /= (mVarianceLength - 1); return wVar; } void iterate(const double value) { const std::size_t currentIndex = mCounter % mVarianceLength; mMeasuredValues[currentIndex] = value; if (mCounter < (mVarianceLength + mVarianceLength)) { if (mCounter == mVarianceLength) { mValue = value; } else { mValue = (mValue + value) / 2; } } else { // prediction equations const double prevFilterValue = mFilterValues[(mCounter - 1) % mVarianceLength]; mFilterValues[currentIndex] = prevFilterValue; mWVariance = calculateWVariance(); const double coVarianceEstimation = mCoVariance + mWVariance; // update equations mVVariance = calculateVVariance(); if ((coVarianceEstimation + mVVariance) != 0) { mGain = coVarianceEstimation / (coVarianceEstimation + mVVariance); } else { mGain = std::numeric_limits::max(); } mValue = prevFilterValue + mGain * (value - prevFilterValue); mCoVariance = (1 - mGain) * coVarianceEstimation; } mFilterValues[currentIndex] = mValue; ++mCounter; } double mValue; double mGain; double mVVariance; double mWVariance; double mCoVariance; size_t mVarianceLength; size_t mCounter; std::array mFilterValues; std::array mMeasuredValues; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/MeasurementService.hpp0000644000175000017500000001255312765602651024135 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace ableton { namespace link { template class MeasurementService { public: using Point = std::pair; using MeasurementInstance = Measurement, Log>; using MeasurementServicePingResponder = PingResponder, Log>; static const std::size_t kNumberThreads = 1; MeasurementService(asio::ip::address_v4 address, SessionId sessionId, GhostXForm ghostXForm, Clock clock, util::Injected log) : mClock(std::move(clock)) , mLog(std::move(log)) , mPingResponder(std::move(address), std::move(sessionId), std::move(ghostXForm), util::injectRef(mIo), mClock, mLog) { } MeasurementService(const MeasurementService&) = delete; MeasurementService(MeasurementService&&) = delete; ~MeasurementService() { // Clear the measurement map in the io service so that whatever // cleanup code executes in response to the destruction of the // measurement objects still have access to the io service mIo.post([this] { mMeasurementMap.clear(); }); } void updateNodeState(const SessionId& sessionId, const GhostXForm& xform) { mPingResponder.updateNodeState(sessionId, xform); } asio::ip::udp::endpoint endpoint() const { return mPingResponder.endpoint(); } // Measure the peer and invoke the handler with a GhostXForm template void measurePeer(const PeerState& state, const Handler handler) { using namespace std; mIo.post([this, state, handler] { const auto nodeId = state.nodeState.nodeId; auto addr = mPingResponder.endpoint().address().to_v4(); auto callback = CompletionCallback{*this, nodeId, handler}; try { mMeasurementMap[nodeId] = MeasurementInstance{state, move(callback), move(addr), mClock, mLog}; } catch (const runtime_error& err) { info(*mLog) << "Failed to measure. Reason: " << err.what(); handler(GhostXForm{}); } }); } static GhostXForm filter( std::vector::const_iterator begin, std::vector::const_iterator end) { using namespace std; using std::chrono::microseconds; Kalman<5> kalman; for (auto it = begin; it != end; ++it) { kalman.iterate(it->second - it->first); } return GhostXForm{1, microseconds(llround(kalman.getValue()))}; } private: template struct CompletionCallback { void operator()(const std::vector data) { using namespace std; using std::chrono::microseconds; // Post this to the measurement service's io service so that we // don't delete the measurement object in its stack. Capture all // needed data separately from this, since this object may be // gone by the time the block gets executed. auto nodeId = mNodeId; auto handler = mHandler; auto& measurementMap = mService.mMeasurementMap; mService.mIo.post([nodeId, handler, &measurementMap, data] { const auto it = measurementMap.find(nodeId); if (it != measurementMap.end()) { if (data.empty()) { handler(GhostXForm{}); } else { handler(MeasurementService::filter(begin(data), end(data))); } measurementMap.erase(it); } }); } MeasurementService& mService; NodeId mNodeId; Handler mHandler; }; // Make sure the measurement map outlives the io service so that the rest of // the members are guaranteed to be valid when any final handlers // are begin run. using MeasurementMap = std::map; MeasurementMap mMeasurementMap; Clock mClock; util::Injected mLog; platforms::asio::AsioService mIo; MeasurementServicePingResponder mPingResponder; }; } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/LinearRegression.hpp0000644000175000017500000000372312765602651023601 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include namespace ableton { namespace link { template std::pair linearRegression(It begin, It end) { using namespace std; using Point = pair; const double numPoints = static_cast(distance(begin, end)); const double meanX = accumulate(begin, end, 0.0, [](double a, Point b) { return a + b.first; }) / numPoints; const double productXX = accumulate(begin, end, 0.0, [&meanX](double a, Point b) { return a + pow(b.first - meanX, 2.0); }); const double meanY = accumulate(begin, end, 0.0, [](double a, Point b) { return a + b.second; }) / numPoints; const double productXY = inner_product(begin, end, begin, 0.0, [](double a, double b) { return a + b; }, [&meanX, &meanY](Point a, Point b) { return ((a.first - meanX) * (b.second - meanY)); }); const double slope = productXX == 0.0 ? 0.0 : productXY / productXX; const double intercept = meanY - (slope * meanX); return make_pair(slope, intercept); } } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/link/Peers.hpp0000644000175000017500000002434712765602651021411 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include namespace ableton { namespace link { // SessionMembershipCallback is invoked when any change to session // membership occurs (when any peer joins or leaves a session) // // SessionTimelineCallback is invoked with a session id and a timeline // whenever a new combination of these values is seen template class Peers { // non-movable private implementation type struct Impl; public: using Peer = std::pair; Peers(util::Injected io, SessionMembershipCallback membership, SessionTimelineCallback timeline) : mpImpl( std::make_shared(std::move(io), std::move(membership), std::move(timeline))) { } // The set of peers for a given session, ordered by (peerId, addr). // The result will possibly contain multiple entries for the same // peer if it is visible through multiple gateways. std::vector sessionPeers(const SessionId& sid) const { using namespace std; vector result; auto& peerVec = mpImpl->mPeers; copy_if(begin(peerVec), end(peerVec), back_inserter(result), SessionMemberPred{sid}); return result; } // Number of individual for a given session. std::size_t uniqueSessionPeerCount(const SessionId& sid) const { using namespace std; auto peerVec = sessionPeers(sid); auto last = unique(begin(peerVec), end(peerVec), [](const Peer& a, const Peer& b) { return a.first.ident() == b.first.ident(); }); return static_cast(distance(begin(peerVec), last)); } void setSessionTimeline(const SessionId& sid, const Timeline& tl) { // Set the cached timeline for all peers to a new client-specified // timeline. When we make a timeline change, we do so // optimistically and clients assume that all peers in a session // have adopted the newly specified timeline. We must represent // this in our cache or else we risk failing to notify about a // higher-priority peer timeline that was already seen. for (auto& peer : mpImpl->mPeers) { if (peer.first.sessionId() == sid) { peer.first.nodeState.timeline = tl; } } } // Purge all cached peers that are members of the given session void forgetSession(const SessionId& sid) { using namespace std; auto& peerVec = mpImpl->mPeers; peerVec.erase( remove_if(begin(peerVec), end(peerVec), SessionMemberPred{sid}), end(peerVec)); } void resetPeers() { mpImpl->mPeers.clear(); } // Observer type that monitors peer discovery on a particular // gateway and relays the information to a Peers instance. // Models the PeerObserver concept from the discovery module. struct GatewayObserver { using GatewayObserverNodeState = PeerState; using GatewayObserverNodeId = NodeId; GatewayObserver(std::shared_ptr pImpl, asio::ip::address addr) : mpImpl(std::move(pImpl)) , mAddr(std::move(addr)) { } GatewayObserver(const GatewayObserver&) = delete; GatewayObserver(GatewayObserver&& rhs) : mpImpl(std::move(rhs.mpImpl)) , mAddr(std::move(rhs.mAddr)) { } ~GatewayObserver() { // Check to handle the moved from case if (mpImpl) { auto& io = *mpImpl->mIo; io.async(Deleter{*this}); } } // model the PeerObserver concept from discovery friend void sawPeer(GatewayObserver& observer, const PeerState& state) { auto pImpl = observer.mpImpl; auto addr = observer.mAddr; assert(pImpl); pImpl->mIo->async([pImpl, addr, state] { pImpl->sawPeerOnGateway(std::move(state), std::move(addr)); }); } friend void peerLeft(GatewayObserver& observer, const NodeId& id) { auto pImpl = observer.mpImpl; auto addr = observer.mAddr; pImpl->mIo->async( [pImpl, addr, id] { pImpl->peerLeftGateway(std::move(id), std::move(addr)); }); } friend void peerTimedOut(GatewayObserver& observer, const NodeId& id) { auto pImpl = observer.mpImpl; auto addr = observer.mAddr; pImpl->mIo->async( [pImpl, addr, id] { pImpl->peerLeftGateway(std::move(id), std::move(addr)); }); } struct Deleter { Deleter(GatewayObserver& observer) : mpImpl(std::move(observer.mpImpl)) , mAddr(std::move(observer.mAddr)) { } void operator()() { mpImpl->gatewayClosed(mAddr); } std::shared_ptr mpImpl; asio::ip::address mAddr; }; std::shared_ptr mpImpl; asio::ip::address mAddr; }; // Factory function for the gateway observer friend GatewayObserver makeGatewayObserver(Peers& peers, asio::ip::address addr) { return GatewayObserver{peers.mpImpl, std::move(addr)}; } private: struct Impl { Impl(util::Injected io, SessionMembershipCallback membership, SessionTimelineCallback timeline) : mIo(std::move(io)) , mSessionMembershipCallback(std::move(membership)) , mSessionTimelineCallback(std::move(timeline)) { } void sawPeerOnGateway(PeerState peerState, asio::ip::address gatewayAddr) { using namespace std; const auto peerSession = peerState.sessionId(); const auto peerTimeline = peerState.timeline(); bool isNewSessionTimeline = false; bool didSessionMembershipChange = false; { isNewSessionTimeline = !sessionTimelineExists(peerSession, peerTimeline); auto peer = make_pair(move(peerState), move(gatewayAddr)); const auto idRange = equal_range(begin(mPeers), end(mPeers), peer, PeerIdComp{}); if (idRange.first == idRange.second) { // This peer is not currently known on any gateway didSessionMembershipChange = true; mPeers.insert(move(idRange.first), move(peer)); } else { // We've seen this peer before... does it have a new session? didSessionMembershipChange = all_of(idRange.first, idRange.second, [&peerSession](const Peer& test) { return test.first.sessionId() != peerSession; }); // was it on this gateway? const auto addrRange = equal_range(idRange.first, idRange.second, peer, AddrComp{}); if (addrRange.first == addrRange.second) { // First time on this gateway, add it mPeers.insert(move(addrRange.first), move(peer)); } else { // We have an entry for this peer on this gateway, update it *addrRange.first = move(peer); } } } // end lock // Invoke callbacks outside the critical section if (isNewSessionTimeline) { mSessionTimelineCallback(peerSession, peerTimeline); } if (didSessionMembershipChange) { mSessionMembershipCallback(); } } void peerLeftGateway(const NodeId& nodeId, const asio::ip::address& gatewayAddr) { using namespace std; bool didSessionMembershipChange = false; { auto it = find_if(begin(mPeers), end(mPeers), [&](const Peer& peer) { return peer.first.ident() == nodeId && peer.second == gatewayAddr; }); if (it != end(mPeers)) { mPeers.erase(move(it)); didSessionMembershipChange = true; } } // end lock if (didSessionMembershipChange) { mSessionMembershipCallback(); } } void gatewayClosed(const asio::ip::address& gatewayAddr) { using namespace std; { mPeers.erase( remove_if(begin(mPeers), end(mPeers), [&gatewayAddr](const Peer& peer) { return peer.second == gatewayAddr; }), end(mPeers)); } // end lock mSessionMembershipCallback(); } bool sessionTimelineExists(const SessionId& session, const Timeline& tl) { using namespace std; return find_if(begin(mPeers), end(mPeers), [&](const Peer& peer) { return peer.first.sessionId() == session && peer.first.timeline() == tl; }) != end(mPeers); } struct PeerIdComp { bool operator()(const Peer& lhs, const Peer& rhs) const { return lhs.first.ident() < rhs.first.ident(); } }; struct AddrComp { bool operator()(const Peer& lhs, const Peer& rhs) const { return lhs.second < rhs.second; } }; util::Injected mIo; SessionMembershipCallback mSessionMembershipCallback; SessionTimelineCallback mSessionTimelineCallback; std::vector mPeers; // sorted by peerId, unique by (peerId, addr) }; struct SessionMemberPred { bool operator()(const Peer& peer) const { return peer.first.sessionId() == sid; } const SessionId& sid; }; std::shared_ptr mpImpl; }; template Peers makePeers( util::Injected io, SessionMembershipCallback membershipCallback, SessionTimelineCallback timelineCallback) { return {std::move(io), std::move(membershipCallback), std::move(timelineCallback)}; } } // namespace link } // namespace ableton link-Link-1.0.0/include/ableton/test/0000755000175000017500000000000012765602651017632 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/test/CatchWrapper.hpp0000644000175000017500000000246612765602651022736 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once /*! * \brief Wrapper file for Catch library * * This file includes the Catch header for Link, and also disables some compiler warnings * which are specific to that library. */ // Visual Studio #if defined(_MSC_VER) #pragma warning(push) // C4388: signed/unsigned mismatch #pragma warning(disable : 4388) // C4702: unreachable code #pragma warning(disable : 4702) #endif #include // Visual Studio #if defined(_MSC_VER) #pragma warning(pop) #endif link-Link-1.0.0/include/ableton/test/serial_io/0000755000175000017500000000000012765602651021600 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/test/serial_io/Timer.hpp0000644000175000017500000000467512765602651023405 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace test { namespace serial_io { struct Timer { using ErrorCode = SchedulerTree::TimerErrorCode; using TimePoint = SchedulerTree::TimePoint; Timer(const SchedulerTree::TimerId timerId, const TimePoint& now, std::shared_ptr pScheduler) : mId(timerId) , mNow(now) , mpScheduler(std::move(pScheduler)) { } ~Timer() { if (!mbMovedFrom) { cancel(); } } Timer(const Timer&) = delete; Timer(Timer&& rhs) : mId(rhs.mId) , mNow(rhs.mNow) , mExpiration(std::move(rhs.mExpiration)) , mpScheduler(std::move(rhs.mpScheduler)) { rhs.mbMovedFrom = true; } void expires_at(const TimePoint t) { if (t < mNow) { throw std::runtime_error("Setting timer in the past"); } else { cancel(); mExpiration = t; } } template void expires_from_now(std::chrono::duration duration) { expires_at(mNow + duration); } void cancel() { auto pScheduler = mpScheduler.lock(); pScheduler->cancelTimer(mId); } template void async_wait(Handler handler) { auto pScheduler = mpScheduler.lock(); pScheduler->setTimer(mId, mExpiration, std::move(handler)); } TimePoint now() const { return mNow; } const SchedulerTree::TimerId mId; const TimePoint& mNow; TimePoint mExpiration; std::weak_ptr mpScheduler; bool mbMovedFrom = false; }; } // namespace serial_io } // namespace test } // namespace ableton link-Link-1.0.0/include/ableton/test/serial_io/Fixture.hpp0000644000175000017500000000435412765602651023745 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include namespace ableton { namespace test { namespace serial_io { class Fixture { public: Fixture() : mpScheduler(std::make_shared()) , mNow(std::chrono::milliseconds{123456789}) { } ~Fixture() { flush(); } Fixture(const Fixture&) = delete; Fixture& operator=(const Fixture&) = delete; Fixture(Fixture&&) = delete; Fixture& operator=(Fixture&&) = delete; void setNetworkInterfaces(std::vector<::asio::ip::address> ifAddrs) { mIfAddrs = std::move(ifAddrs); } Context makeIoContext() { return {mNow, mIfAddrs, mpScheduler}; } void flush() { mpScheduler->run(); } template void advanceTime(std::chrono::duration duration) { const auto target = mNow + duration; mpScheduler->run(); auto nextTimer = mpScheduler->nextTimerExpiration(); while (nextTimer <= target) { mNow = nextTimer; mpScheduler->triggerTimersUntil(mNow); mpScheduler->run(); nextTimer = mpScheduler->nextTimerExpiration(); } mNow = target; } private: std::shared_ptr mpScheduler; SchedulerTree::TimePoint mNow; std::vector<::asio::ip::address> mIfAddrs; }; } // namespace serial_io } // namespace test } // namespace ableton link-Link-1.0.0/include/ableton/test/serial_io/Context.hpp0000644000175000017500000000503712765602651023742 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include #include namespace ableton { namespace test { namespace serial_io { class Context { public: Context(const SchedulerTree::TimePoint& now, const std::vector<::asio::ip::address>& ifAddrs, std::shared_ptr pScheduler) : mNow(now) , mIfAddrs(ifAddrs) , mpScheduler(std::move(pScheduler)) , mNextTimerId(0) { } ~Context() { if (mpScheduler != nullptr) { // Finish any pending tasks before shutting down mpScheduler->run(); } } Context(const Context&) = delete; Context& operator=(const Context&) = delete; Context(Context&& rhs) : mNow(rhs.mNow) , mIfAddrs(rhs.mIfAddrs) , mpScheduler(std::move(rhs.mpScheduler)) , mLog(std::move(rhs.mLog)) , mNextTimerId(rhs.mNextTimerId) { } template void async(Handler handler) { mpScheduler->async(std::move(handler)); } Context clone() { return {mNow, mIfAddrs, mpScheduler->makeChild()}; } using Timer = serial_io::Timer; Timer makeTimer() { return {mNextTimerId++, mNow, mpScheduler}; } using Log = util::NullLog; Log& log() { return mLog; } std::vector<::asio::ip::address> scanNetworkInterfaces() { return mIfAddrs; } private: const SchedulerTree::TimePoint& mNow; const std::vector<::asio::ip::address>& mIfAddrs; std::shared_ptr mpScheduler; Log mLog; SchedulerTree::TimerId mNextTimerId; }; } // namespace serial_io } // namespace test } // namespace ableton link-Link-1.0.0/include/ableton/test/serial_io/SchedulerTree.hpp0000644000175000017500000000534512765602651025056 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include #include #include #include namespace ableton { namespace test { namespace serial_io { class SchedulerTree { public: using TimePoint = std::chrono::system_clock::time_point; using TimerId = std::size_t; using TimerErrorCode = int; void run(); std::shared_ptr makeChild(); template void async(Handler handler) { mPendingHandlers.push_back(std::move(handler)); } template void setTimer(const TimerId timerId, const TimePoint expiration, Handler handler) { using namespace std; mTimers[make_pair(move(expiration), timerId)] = move(handler); } void cancelTimer(const TimerId timerId); // returns the time that the next timer in the subtree expires TimePoint nextTimerExpiration(); // triggers all timers in the subtree that expire at time t or before void triggerTimersUntil(const TimePoint t); private: // returns true if some work was done, false if there was none to do bool handlePending(); // returns the time that the next timer from this node expires TimePoint nextOwnTimerExpiration(); // Traversal function over children that cleans up children that // have been destroyed. template void withChildren(Fn fn) { auto it = begin(mChildren); while (it != end(mChildren)) { const auto childIt = it++; auto pChild = childIt->lock(); if (pChild) { fn(*pChild); } else { mChildren.erase(childIt); } } } using TimerHandler = std::function; using TimerMap = std::map, TimerHandler>; TimerMap mTimers; std::list> mPendingHandlers; std::list> mChildren; }; } // namespace serial_io } // namespace test } // namespace ableton link-Link-1.0.0/include/ableton/test/serial_io/Socket.hpp0000644000175000017500000000433212765602651023543 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace test { namespace serial_io { struct Socket { using SendFn = std::function; struct ReceiveHandler { template void operator()(const asio::ip::udp::endpoint& from, const It begin, const It end) { std::vector buffer{begin, end}; mReceive(from, buffer); } std::function&> mReceive; }; using ReceiveFn = std::function; Socket(SendFn sendFn, ReceiveFn receiveFn) : mSendFn(std::move(sendFn)) , mReceiveFn(std::move(receiveFn)) { } std::size_t send( const uint8_t* const pData, const size_t numBytes, const asio::ip::udp::endpoint& to) { return mSendFn(pData, numBytes, to); } template void receive(Handler handler) { mReceiveFn(ReceiveHandler{ [handler](const asio::ip::udp::endpoint& from, const std::vector& buffer) { handler(from, begin(buffer), end(buffer)); }}); } asio::ip::udp::endpoint endpoint() const { return asio::ip::udp::endpoint({}, 0); } SendFn mSendFn; ReceiveFn mReceiveFn; }; } // namespace test } // namespace platforms } // namespace ableton link-Link-1.0.0/include/ableton/util/0000755000175000017500000000000012765602651017630 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/util/test/0000755000175000017500000000000012765602651020607 5ustar zmoelnigzmoelniglink-Link-1.0.0/include/ableton/util/test/IoService.hpp0000644000175000017500000000471212765602651023214 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace util { namespace test { struct IoService { // Wrapper around the internal util::test::Timer in the list struct Timer { using ErrorCode = test::Timer::ErrorCode; using TimePoint = test::Timer::TimePoint; Timer(util::test::Timer* pTimer) : mpTimer(pTimer) { } void expires_at(std::chrono::system_clock::time_point t) { mpTimer->expires_at(t); } template void expires_from_now(std::chrono::duration duration) { mpTimer->expires_from_now(duration); } ErrorCode cancel() { return mpTimer->cancel(); } template void async_wait(Handler handler) { mpTimer->async_wait(std::move(handler)); } TimePoint now() const { return mpTimer->now(); } util::test::Timer* mpTimer; }; IoService() = default; Timer makeTimer() { mTimers.emplace_back(); return Timer{&mTimers.back()}; } template void post(Handler handler) { mHandlers.emplace_back(std::move(handler)); } template void advance(std::chrono::duration duration) { runHandlers(); for (auto& timer : mTimers) { timer.advance(duration); } } void runHandlers() { for (auto& handler : mHandlers) { handler(); } mHandlers.clear(); } std::vector> mHandlers; std::vector mTimers; }; } // namespace test } // namespace util } // namespace ableton link-Link-1.0.0/include/ableton/util/test/Timer.hpp0000644000175000017500000000437612765602651022412 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include #include namespace ableton { namespace util { namespace test { struct Timer { using ErrorCode = int; using TimePoint = std::chrono::system_clock::time_point; // Initialize timer with an arbitrary large value to simulate the // time_since_epoch of a real clock. Timer() : mNow{std::chrono::milliseconds{123456789}} { } void expires_at(std::chrono::system_clock::time_point t) { cancel(); mFireAt = std::move(t); } template void expires_from_now(std::chrono::duration duration) { cancel(); mFireAt = now() + duration; } ErrorCode cancel() { if (mHandler) { mHandler(1); // call existing handler with truthy error code } mHandler = nullptr; return 0; } template void async_wait(Handler handler) { mHandler = [handler](ErrorCode ec) { handler(ec); }; } std::chrono::system_clock::time_point now() const { return mNow; } template void advance(std::chrono::duration duration) { mNow += duration; if (mHandler && mFireAt < mNow) { mHandler(0); mHandler = nullptr; } } std::function mHandler; std::chrono::system_clock::time_point mFireAt; std::chrono::system_clock::time_point mNow; }; } // namespace test } // namespace util } // namespace ableton link-Link-1.0.0/include/ableton/util/SampleTiming.hpp0000644000175000017500000000304612765602651022735 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace util { /*! Utility type to convert between time and sample index given the * time at the beginning of a buffer and the sample rate. */ struct SampleTiming { double sampleAtTime(std::chrono::microseconds time) const { using namespace std::chrono; return duration_cast>(time - mBufferBegin).count() * mSampleRate; } std::chrono::microseconds timeAtSample(const double sample) const { using namespace std::chrono; return mBufferBegin + duration_cast(duration{sample / mSampleRate}); } std::chrono::microseconds mBufferBegin; double mSampleRate; }; } // util } // ableton link-Link-1.0.0/include/ableton/util/SafeAsyncHandler.hpp0000644000175000017500000000372612765602651023523 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace util { // A utility handler for passing to async functions that may call the // handler past the lifetime of the wrapped delegate object. // The need for this is particularly driven by boost::asio timer // objects, which explicitly document that they may be called without // an error code after they have been cancelled. This has led to // several crashes. This handler wrapper implements a useful idiom for // avoiding this problem. template struct SafeAsyncHandler { SafeAsyncHandler(const std::shared_ptr& pDelegate) : mpDelegate(pDelegate) { } template void operator()(T&&... t) const { std::shared_ptr pDelegate = mpDelegate.lock(); if (pDelegate) { (*pDelegate)(std::forward(t)...); } } std::weak_ptr mpDelegate; }; // Factory function for easily wrapping a shared_ptr to a handler template SafeAsyncHandler makeAsyncSafe(const std::shared_ptr& pDelegate) { return {pDelegate}; } } // namespace util } // namespace ableton link-Link-1.0.0/include/ableton/util/Injected.hpp0000644000175000017500000001051212765602651022065 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include namespace ableton { namespace util { // Utility type for aiding in dependency injection. // Base template and implementation for injected valued template struct Injected { using type = T; Injected() = default; explicit Injected(T t) : val(std::move(t)) { } Injected(const Injected&) = default; Injected& operator=(const Injected&) = default; Injected(Injected&& rhs) : val(std::move(rhs.val)) { } Injected& operator=(Injected&& rhs) { val = std::move(rhs.val); return *this; } T* operator->() { return &val; } const T* operator->() const { return &val; } T& operator*() { return val; } const T& operator*() const { return val; } T val; }; // Utility function for injecting values template Injected injectVal(T t) { return Injected(std::move(t)); } // Specialization for injected references template struct Injected { using type = T; explicit Injected(T& t) : ref(std::ref(t)) { } Injected(const Injected&) = default; Injected& operator=(const Injected&) = default; Injected(Injected&& rhs) : ref(std::move(rhs.ref)) { } Injected& operator=(Injected&& rhs) { ref = std::move(rhs.ref); return *this; } T* operator->() { return &ref.get(); } const T* operator->() const { return &ref.get(); } T& operator*() { return ref; } const T& operator*() const { return ref; } std::reference_wrapper ref; }; // Utility function for injecting references template Injected injectRef(T& t) { return Injected(t); } // Specialization for injected shared_ptr template struct Injected> { using type = T; explicit Injected(std::shared_ptr pT) : shared(std::move(pT)) { } Injected(const Injected&) = default; Injected& operator=(const Injected&) = default; Injected(Injected&& rhs) : shared(std::move(rhs.shared)) { } Injected& operator=(Injected&& rhs) { shared = std::move(rhs.shared); return *this; } T* operator->() { return shared.get(); } const T* operator->() const { return shared.get(); } T& operator*() { return *shared; } const T& operator*() const { return *shared; } std::shared_ptr shared; }; // Utility function for injected shared_ptr template Injected> injectShared(std::shared_ptr shared) { return Injected>(std::move(shared)); } // Specialization for injected unique_ptr template struct Injected> { using type = T; explicit Injected(std::unique_ptr pT) : unique(std::move(pT)) { } Injected(const Injected&) = default; Injected& operator=(const Injected&) = default; Injected(Injected&& rhs) : unique(std::move(rhs.unique)) { } Injected& operator=(Injected&& rhs) { unique = std::move(rhs.unique); return *this; } T* operator->() { return unique.get(); } const T* operator->() const { return unique.get(); } T& operator*() { return *unique; } const T& operator*() const { return *unique; } std::unique_ptr unique; }; // Utility function for injected unique_ptr template Injected> injectUnique(std::unique_ptr unique) { return Injected>(std::move(unique)); } } // namespace util } // namespace ableton link-Link-1.0.0/include/ableton/util/Log.hpp0000644000175000017500000000704612765602651021071 0ustar zmoelnigzmoelnig// Copyright: 2014, Ableton AG, Berlin, all rights reserved #pragma once #include #include #include namespace ableton { namespace util { // Null object for the Log concept struct NullLog { template friend const NullLog& operator<<(const NullLog& log, const T&) { return log; } friend const NullLog& debug(const NullLog& log) { return log; } friend const NullLog& info(const NullLog& log) { return log; } friend const NullLog& warning(const NullLog& log) { return log; } friend const NullLog& error(const NullLog& log) { return log; } friend NullLog channel(const NullLog&, std::string) { return {}; } }; // std streams-based log struct StdLog { StdLog(std::string channelName = "") : mChannelName(std::move(channelName)) { } // Stream type used by std log to prepend the channel name to log messages struct StdLogStream { StdLogStream(std::ostream& ioStream, const std::string& channelName) : mpIoStream(&ioStream) , mChannelName(channelName) { ioStream << "[" << mChannelName << "] "; } StdLogStream(StdLogStream&& rhs) : mpIoStream(rhs.mpIoStream) , mChannelName(rhs.mChannelName) { rhs.mpIoStream = nullptr; } ~StdLogStream() { if (mpIoStream) { (*mpIoStream) << "\n"; } } template std::ostream& operator<<(const T& rhs) { (*mpIoStream) << rhs; return *mpIoStream; } std::ostream* mpIoStream; const std::string& mChannelName; }; friend StdLogStream debug(const StdLog& log) { return {std::clog, log.mChannelName}; } friend StdLogStream info(const StdLog& log) { return {std::clog, log.mChannelName}; } friend StdLogStream warning(const StdLog& log) { return {std::clog, log.mChannelName}; } friend StdLogStream error(const StdLog& log) { return {std::cerr, log.mChannelName}; } friend StdLog channel(const StdLog& log, const std::string& channelName) { auto compositeName = log.mChannelName.empty() ? channelName : log.mChannelName + "::" + channelName; return {std::move(compositeName)}; } std::string mChannelName; }; // Log adapter that adds timestamps template struct Timestamped { using InnerLog = typename util::Injected::type; Timestamped() = default; Timestamped(util::Injected log) : mLog(std::move(log)) { } util::Injected mLog; friend decltype(debug(std::declval())) debug(const Timestamped& log) { return log.logTimestamp(debug(*log.mLog)); } friend decltype(info(std::declval())) info(const Timestamped& log) { return log.logTimestamp(info(*log.mLog)); } friend decltype(warning(std::declval())) warning(const Timestamped& log) { return log.logTimestamp(warning(*log.mLog)); } friend decltype(error(std::declval())) error(const Timestamped& log) { return log.logTimestamp(error(*log.mLog)); } friend Timestamped channel(const Timestamped& log, const std::string& channelName) { return {channel(*log.mLog, channelName)}; } template Stream logTimestamp(Stream&& streamRef) const { using namespace std::chrono; Stream stream = std::forward(streamRef); stream << "|" << duration_cast(system_clock::now().time_since_epoch()).count() << "ms| "; return stream; } }; } // namespace util } // namespace ableton link-Link-1.0.0/ci/0000755000175000017500000000000012765602651014177 5ustar zmoelnigzmoelniglink-Link-1.0.0/ci/build.py0000755000175000017500000000353712765602651015663 0ustar zmoelnigzmoelnig#!/usr/bin/env python import argparse import logging import os import sys from distutils.spawn import find_executable from subprocess import call def parse_args(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument( '--cmake', default=find_executable("cmake"), help='Path to CMake executable (default: %(default)s)') arg_parser.add_argument( '-c', '--configuration', help='Build configuration to use (not supported by IDE generators)') arg_parser.add_argument( '-a', '--arguments', help='Arguments to pass to builder') return arg_parser.parse_args(sys.argv[1:]) def build_cmake_args(args, build_dir): if args.cmake is None: logging.error('CMake not found, please use the --cmake option') return None cmake_args = [] cmake_args.append(args.cmake) cmake_args.append('--build') cmake_args.append(build_dir) if args.configuration is not None: cmake_args.append('--config') cmake_args.append(args.configuration) if args.arguments is not None: cmake_args.append('--') for arg in args.arguments.split(): cmake_args.append(arg) return cmake_args def build(args): scripts_dir = os.path.dirname(os.path.realpath(__file__)) root_dir = os.path.join(scripts_dir, os.pardir) build_dir = os.path.join(root_dir, 'build') if not os.path.exists(build_dir): logging.error( 'Build directory not found, did you forget to run the configure.py script?') return 2 cmake_args = build_cmake_args(args, build_dir) if cmake_args is None: return 1 logging.info('Running CMake') return call(cmake_args) if __name__ == '__main__': logging.basicConfig(format='%(message)s', level=logging.INFO, stream=sys.stdout) sys.exit(build(parse_args())) link-Link-1.0.0/ci/check-formatting.py0000755000175000017500000000427412765602651020010 0ustar zmoelnigzmoelnig#!/usr/bin/env python import argparse import logging import os import subprocess import sys def parse_args(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument( '-c', '--clang-format', default='clang-format-3.7', help='Path to clang-format executable') return arg_parser.parse_args(sys.argv[1:]) def parse_clang_xml(xml): for line in xml.splitlines(): if line.startswith(' /dev/null; done elif [ "$wordsize" -eq 32 ]; then wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.gcc/5.5.1-0qt5_essentials.7z && wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.gcc/5.5.1-0icu-linux-g++-Rhel6.6-x86.7z && wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.qtquick1.gcc/5.5.1-0qt5_qtquick1.7z && wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.qtwebengine.gcc/5.5.1-0qt5_qtwebengine.7z && wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.gcc/5.5.1-0qt5_addons.7z && wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.qtscript.gcc/5.5.1-0qt5_qtscript.7z && wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.qtlocation.gcc/5.5.1-0qt5_qtlocation.7z && wget http://download.qt.io/online/qtsdkrepository/linux_x86/desktop/qt5_55/qt.55.gcc/5.5.1-0qt5_qtpositioning.7z && for i in *.7z; do 7z x "$i" > /dev/null; done else echo "usage: ./install-qt-5.sh wordsize" fi link-Link-1.0.0/ci/memcheck.supp0000644000175000017500000000076312765602651016672 0ustar zmoelnigzmoelnig# These Glibc-related leaks are common when running Valgrind. For more info, # see http://valgrind.org/docs/manual/faq.html#faq.reports { glibc-memory-pool-64-bit Memcheck:Leak fun:malloc obj:/usr/lib/x86_64-linux-gnu/libstdc++.so.6.* fun:call_init.part.0 ... fun:_dl_init obj:/lib/x86_64-linux-gnu/ld-*.so } { glibc-memory-pool-32-bit Memcheck:Leak fun:malloc obj:/usr/lib32/libstdc++.so.6.* fun:call_init fun:_dl_init obj:/lib/i386-linux-gnu/ld-*.so } link-Link-1.0.0/ci/run_valgrind_tests.sh0000755000175000017500000000026212765602651020452 0ustar zmoelnigzmoelnig#!/bin/bash python configure.py --generator Ninja python build.py python run-tests.py --target LinkCoreTest --valgrind python run-tests.py --target LinkDiscoveryTest --valgrind link-Link-1.0.0/ci/run-tests.py0000755000175000017500000000510112765602651016515 0ustar zmoelnigzmoelnig#!/usr/bin/env python import argparse import logging import os import sys from distutils.spawn import find_executable from subprocess import call def parse_args(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument( '-t', '--target', help='Target to test') arg_parser.add_argument( '--valgrind', default=False, help='Run with Valgrind', action='store_true') return arg_parser.parse_args(sys.argv[1:]) def get_system_exe_extension(): # Should return 'win32' even on 64-bit Windows if sys.platform == 'win32': return '.exe' else: return '' def find_exe(name, path): for root, dirs, files in os.walk(path): if name in files: return os.path.join(root, name) def build_test_exe_args(args, build_dir): if args.target is None: logging.error('Target not specified, please use the --target option') return None test_exe = find_exe(args.target + get_system_exe_extension(), build_dir) if not os.path.exists(test_exe): logging.error('Could not find test executable for target {}, ' 'did you forget to build?'.format(args.target)) else: logging.debug('Test executable is: {}'.format(test_exe)) test_exe_args = [test_exe] if args.valgrind is not False: valgrind_exe = find_executable('valgrind') if valgrind_exe is None: logging.error('Valgrind not found, cannot continue') return None test_exe_args = [ valgrind_exe, '--leak-check=full', '--show-reachable=yes', '--gen-suppressions=all', '--error-exitcode=1', '--track-origins=yes', '--suppressions=../ci/memcheck.supp', test_exe] return test_exe_args def run_tests(args): scripts_dir = os.path.dirname(os.path.realpath(__file__)) root_dir = os.path.join(scripts_dir, os.pardir) build_dir = os.path.join(root_dir, 'build') if not os.path.exists(build_dir): logging.error( 'Build directory not found, did you forget to run the configure.py script?') return 2 os.chdir(build_dir) env = os.environ.copy() env['GLIBCXX_FORCE_NEW'] = '1' test_exe_args = build_test_exe_args(args, build_dir) if test_exe_args is None: return 1 logging.info(test_exe_args) logging.info('Running Tests for {}'.format(args.target)) return call(test_exe_args, env=env) if __name__ == '__main__': logging.basicConfig(format='%(message)s', level=logging.INFO, stream=sys.stdout) sys.exit(run_tests(parse_args())) link-Link-1.0.0/GNU-GPL-v2.0.md0000644000175000017500000004302512765602651015666 0ustar zmoelnigzmoelnigGNU General Public License ========================== _Version 2, June 1991_ _Copyright © 1989, 1991 Free Software Foundation, Inc.,_ _51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA_ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ### Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: **(1)** copyright the software, and **(2)** offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. ### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION **0.** This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The “Program”, below, refers to any such program or work, and a “work based on the Program” means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term “modification”.) Each licensee is addressed as “you”. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. **1.** You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. **2.** You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: * **a)** You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. * **b)** You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. * **c)** If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. **3.** You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: * **a)** Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, * **b)** Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, * **c)** Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. **4.** You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. **5.** You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. **6.** Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. **7.** If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. **8.** If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. **9.** The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and “any later version”, you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. **10.** If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. ### NO WARRANTY **11.** BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. **12.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ### How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w` and `show c` should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w` and `show c`; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a “copyright disclaimer” for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. link-Link-1.0.0/LICENSE.md0000644000175000017500000000144112765602651015210 0ustar zmoelnigzmoelnig# License Copyright 2016, Ableton AG, Berlin. All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . If you would like to incorporate Link into a proprietary software application, please contact . link-Link-1.0.0/src/0000755000175000017500000000000012765602651014373 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/CMakeLists.txt0000644000175000017500000000624312765602651017140 0ustar zmoelnigzmoelnigcmake_minimum_required(VERSION 3.0) project(LinkTest) # ____ # / ___| ___ _ _ _ __ ___ ___ ___ # \___ \ / _ \| | | | '__/ __/ _ \/ __| # ___) | (_) | |_| | | | (_| __/\__ \ # |____/ \___/ \__,_|_| \___\___||___/ # set(link_discovery_test_SOURCES ableton/discovery/tst_InterfaceScanner.cpp ableton/discovery/tst_Payload.cpp ableton/discovery/tst_PeerGateway.cpp ableton/discovery/tst_PeerGateways.cpp ableton/discovery/tst_UdpMessenger.cpp ableton/discovery/v1/tst_Messages.cpp ) set(link_core_test_SOURCES ableton/link/tst_Beats.cpp ableton/link/tst_ClientSessionTimelines.cpp ableton/link/tst_Controller.cpp ableton/link/tst_HostTimeFilter.cpp ableton/link/tst_Kalman.cpp ableton/link/tst_LinearRegression.cpp ableton/link/tst_Measurement.cpp ableton/link/tst_Peers.cpp ableton/link/tst_Phase.cpp ableton/link/tst_PingResponder.cpp ableton/link/tst_Tempo.cpp ableton/link/tst_Timeline.cpp ) set(link_test_SOURCES ableton/test/catch/CatchMain.cpp ableton/test/serial_io/SchedulerTree.cpp ) # ____ ____ # / ___| ___ _ _ _ __ ___ ___ / ___|_ __ ___ _ _ _ __ ___ # \___ \ / _ \| | | | '__/ __/ _ \ | | _| '__/ _ \| | | | '_ \/ __| # ___) | (_) | |_| | | | (_| __/ | |_| | | | (_) | |_| | |_) \__ \ # |____/ \___/ \__,_|_| \___\___| \____|_| \___/ \__,_| .__/|___/ # |_| source_group("Link" FILES ${link_core_HEADERS} ) source_group("Discovery" FILES ${link_discovery_HEADERS} ) source_group("Platform" FILES ${link_platform_HEADERS} ) source_group("Util" FILES ${link_util_HEADERS} ) source_group("Test Utils" FILES ${link_test_HEADERS} ${link_test_SOURCES} ) # _____ _ # |_ _|_ _ _ __ __ _ ___| |_ ___ # | |/ _` | '__/ _` |/ _ \ __|/ __| # | | (_| | | | (_| | __/ |_ \__ \ # |_|\__,_|_| \__, |\___|\__||___/ # |___/ function(configure_link_test_executable target) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") target_link_libraries(${target} pthread) endif() target_link_libraries(${target} Catch::Catch Ableton::Link) target_set_word_size(${target}) endfunction() # For the LinkCore test suite, we add header dependencies individually so that # the source groups above are shown correctly to the project. However, most # other projects integrating Link won't need this functionality, and they should # should just depend on ${link_HEADERS}. add_executable(LinkCoreTest ${link_core_HEADERS} ${link_discovery_HEADERS} ${link_platform_HEADERS} ${link_util_HEADERS} ${link_test_HEADERS} ${link_core_test_SOURCES} ${link_test_SOURCES} ) configure_link_test_executable(LinkCoreTest) # For the LinkDiscovery test suite, we only add dependencies on the headers # necessary to compile these tests, since the Discovery feature should not have # dependencies on the Link core code. Normal targets should always use # ${link_HEADERS} for their dependencies. add_executable(LinkDiscoveryTest ${link_discovery_HEADERS} ${link_platform_HEADERS} ${link_util_HEADERS} ${link_test_HEADERS} ${link_discovery_test_SOURCES} ${link_test_SOURCES} ) configure_link_test_executable(LinkDiscoveryTest) link-Link-1.0.0/src/ableton/0000755000175000017500000000000012765602651016017 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/ableton/discovery/0000755000175000017500000000000012765602651020026 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/ableton/discovery/v1/0000755000175000017500000000000012765602651020354 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/ableton/discovery/v1/tst_Messages.cpp0000644000175000017500000000502512765602651023523 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include namespace ableton { namespace discovery { namespace v1 { namespace { // For testing just use a single byte identifier using NodeId = uint8_t; } // anonymous namespace TEST_CASE("ParseEmptyBuffer", "[Messages]") { const std::array buffer{}; auto result = parseMessageHeader(begin(buffer), end(buffer)); CHECK(kInvalid == result.first.messageType); CHECK(begin(buffer) == result.second); } TEST_CASE("ParseTruncatedMessageHeader", "[Messages]") { const std::array truncated = { {'_', 'a', 's', 'd', 'p', '_', 'v', 1, 'x', 'y'}}; const auto result = parseMessageHeader(begin(truncated), end(truncated)); CHECK(kInvalid == result.first.messageType); const auto consumedBytes = (begin(truncated) != result.second); CHECK_FALSE(consumedBytes); } TEST_CASE("MissingProtocolHeader", "[Messages]") { // Buffer should be large enough to proceed but shouldn't match the protocol header const std::array zeros{}; auto result = parseMessageHeader(begin(zeros), end(zeros)); CHECK(kInvalid == result.first.messageType); CHECK(begin(zeros) == result.second); } TEST_CASE("RoundtripAliveNoPayload", "[Messages]") { std::array buffer{}; const uint8_t ident = 1; const auto endAlive = aliveMessage(ident, 5, makePayload(), begin(buffer)); const auto result = parseMessageHeader(begin(buffer), endAlive); CHECK(endAlive == result.second); CHECK(kAlive == result.first.messageType); CHECK(5 == result.first.ttl); CHECK(ident == result.first.ident); } } // namespace v1 } // namespace discovery } // namespace ableton link-Link-1.0.0/src/ableton/discovery/tst_UdpMessenger.cpp0000644000175000017500000001673012765602651024034 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include #include #include namespace ableton { namespace discovery { namespace { struct TestNodeState { using IdType = uint8_t; IdType ident() const { return nodeId; } friend auto toPayload(const TestNodeState& state) -> decltype(makePayload(test::Foo{})) { return makePayload(test::Foo{state.fooVal}); } template static TestNodeState fromPayload(const uint8_t id, It begin, It end) { TestNodeState state = {id, 0}; parsePayload( begin, end, [&state](const test::Foo& foo) { state.fooVal = foo.fooVal; }); return state; } IdType nodeId; int32_t fooVal; }; // Test data for a simulated peer const TestNodeState peerState = {5, 15}; const asio::ip::udp::endpoint peerEndpoint = { asio::ip::address::from_string("123.123.234.234"), 1900}; } // anonymous namespace TEST_CASE("UdpMessenger | BroadcastsStateOnConstruction", "[UdpMessenger]") { ::ableton::test::serial_io::Fixture io; auto context = io.makeIoContext(); const auto state = TestNodeState{3, 10}; auto iface = test::Interface{}; auto messenger = makeUdpMessenger(util::injectRef(iface), state, util::injectRef(context), 1, 1); REQUIRE(1 == iface.sentMessages.size()); const auto messageBuffer = iface.sentMessages[0].first; const auto sentTo = iface.sentMessages[0].second; const auto result = v1::parseMessageHeader( begin(messageBuffer), end(messageBuffer)); // Expect an Alive header CHECK(v1::kAlive == result.first.messageType); CHECK(state.nodeId == result.first.ident); CHECK(1 == result.first.ttl); // Sent to the multicast endpoint CHECK(multicastEndpoint() == sentTo); // And the payload should parse to equal to the original state const auto actualState = TestNodeState::fromPayload(state.nodeId, result.second, end(messageBuffer)); CHECK(state.fooVal == actualState.fooVal); } TEST_CASE("UdpMessenger | Heartbeat", "[UdpMessenger]") { ::ableton::test::serial_io::Fixture io; const auto state = TestNodeState{3, 10}; auto iface = test::Interface{}; auto messenger = makeUdpMessenger( util::injectRef(iface), state, util::injectVal(io.makeIoContext()), 4, 2); REQUIRE(1 == iface.sentMessages.size()); // At two seconds the messenger should have broadcasted its state again io.advanceTime(std::chrono::seconds(3)); CHECK(2 == iface.sentMessages.size()); } TEST_CASE("UdpMessenger | Response", "[UdpMessenger]") { ::ableton::test::serial_io::Fixture io; const auto state = TestNodeState{3, 10}; auto iface = test::Interface{}; auto messenger = makeUdpMessenger( util::injectRef(iface), state, util::injectVal(io.makeIoContext()), 1, 1); // Simulate state broadcast from peer, leaving out details like payload v1::MessageBuffer buffer; const auto messageEnd = v1::aliveMessage(peerState.ident(), 0, makePayload(), begin(buffer)); iface.incomingMessage(peerEndpoint, begin(buffer), messageEnd); // The messenger should have responded to the alive message with its // current state REQUIRE(2 == iface.sentMessages.size()); const auto messageBuffer = iface.sentMessages[1].first; const auto sentTo = iface.sentMessages[1].second; const auto result = v1::parseMessageHeader( begin(messageBuffer), end(messageBuffer)); CHECK(v1::kResponse == result.first.messageType); CHECK(state.nodeId == result.first.ident); CHECK(1 == result.first.ttl); CHECK(peerEndpoint == sentTo); } namespace { struct TestHandler { void operator()(PeerState state) { peerStates.push_back(std::move(state)); } void operator()(ByeBye byeBye) { byeByes.push_back(std::move(byeBye)); } std::vector> peerStates; std::vector> byeByes; }; } // unnamed TEST_CASE("UdpMessenger | Receive", "[UdpMessenger]") { ::ableton::test::serial_io::Fixture io; auto iface = test::Interface{}; auto tmpMessenger = makeUdpMessenger( util::injectRef(iface), TestNodeState{}, util::injectVal(io.makeIoContext()), 1, 1); auto messenger = std::move(tmpMessenger); auto handler = TestHandler{}; messenger.receive(std::ref(handler)); v1::MessageBuffer buffer; // Receive an alive message auto end = v1::aliveMessage(peerState.nodeId, 3, toPayload(peerState), begin(buffer)); iface.incomingMessage(peerEndpoint, begin(buffer), end); // And a bye bye message end = v1::byeByeMessage(peerState.nodeId, begin(buffer)); messenger.receive(std::ref(handler)); iface.incomingMessage(peerEndpoint, begin(buffer), end); REQUIRE(1 == handler.peerStates.size()); CHECK(3 == handler.peerStates[0].ttl); CHECK(peerState.nodeId == handler.peerStates[0].peerState.nodeId); CHECK(peerState.fooVal == handler.peerStates[0].peerState.fooVal); REQUIRE(1 == handler.byeByes.size()); CHECK(peerState.nodeId == handler.byeByes[0].peerId); } TEST_CASE("UdpMessenger | SendByeByeOnDestruction", "[UdpMessenger]") { ::ableton::test::serial_io::Fixture io; auto iface = test::Interface{}; { auto messenger = makeUdpMessenger(util::injectRef(iface), TestNodeState{5, 10}, util::injectVal(io.makeIoContext()), 1, 1); } REQUIRE(2 == iface.sentMessages.size()); const auto messageBuffer = iface.sentMessages[1].first; const auto sentTo = iface.sentMessages[1].second; const auto result = v1::parseMessageHeader( begin(messageBuffer), end(messageBuffer)); CHECK(v1::kByeBye == result.first.messageType); CHECK(multicastEndpoint() == sentTo); } namespace { template struct MessengerWrapper { MessengerWrapper(Messenger messenger) : mMessenger(std::move(messenger)) { } Messenger mMessenger; }; template MessengerWrapper wrapMessenger(Messenger messenger) { return {std::move(messenger)}; } } TEST_CASE("UdpMessenger | MovingMessengerDoesntSendByeBye", "[UdpMessenger]") { ::ableton::test::serial_io::Fixture io; // The destructor for the messenger is written so that if an // instance is moved from, it won't send the bye bye message. auto iface = test::Interface{}; { auto messenger = makeUdpMessenger(util::injectRef(iface), TestNodeState{5, 10}, util::injectVal(io.makeIoContext()), 1, 1); auto wrapper = wrapMessenger(std::move(messenger)); } // We should have an initial Alive and then a single ByeBye CHECK(2 == iface.sentMessages.size()); } } // namespace discovery } // namespace ableton link-Link-1.0.0/src/ableton/discovery/tst_PeerGateways.cpp0000644000175000017500000001015112765602651024022 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include namespace ableton { namespace discovery { namespace { struct Gateway { asio::ip::address addr; }; struct NodeState { }; struct Factory { template Gateway operator()(NodeState, util::Injected, const asio::ip::address& addr) { return {addr}; } }; const asio::ip::address addr1 = asio::ip::address::from_string("192.192.192.1"); const asio::ip::address addr2 = asio::ip::address::from_string("192.192.192.2"); template void expectGatewaysAsync( Gateways& gateways, test::serial_io::Fixture& io, std::vector addrs) { using namespace std; using GatewayIt = typename Gateways::GatewayMap::iterator; bool bTested = false; gateways.withGatewaysAsync([addrs, &bTested](GatewayIt begin, const GatewayIt end) { bTested = true; REQUIRE(static_cast(distance(begin, end)) == addrs.size()); std::size_t i = 0; for (; begin != end; ++begin) { CHECK(begin->first == addrs[i++]); } }); io.flush(); CHECK(bTested); } } // anonymous namespace TEST_CASE("PeerGateways | EmptyIfNoInterfaces", "[PeerGateways]") { test::serial_io::Fixture io; auto pGateways = makePeerGateways( std::chrono::seconds(2), NodeState{}, Factory{}, util::injectVal(io.makeIoContext())); pGateways->enable(true); expectGatewaysAsync(*pGateways, io, {}); } TEST_CASE("PeerGateways | MatchesAfterInitialScan", "[PeerGateways]") { test::serial_io::Fixture io; io.setNetworkInterfaces({addr1, addr2}); auto pGateways = makePeerGateways( std::chrono::seconds(2), NodeState{}, Factory{}, util::injectVal(io.makeIoContext())); pGateways->enable(true); expectGatewaysAsync(*pGateways, io, {addr1, addr2}); } TEST_CASE("PeerGateways | GatewayAppears", "[PeerGateways]") { test::serial_io::Fixture io; io.setNetworkInterfaces({addr1}); auto pGateways = makePeerGateways( std::chrono::seconds(2), NodeState{}, Factory{}, util::injectVal(io.makeIoContext())); pGateways->enable(true); expectGatewaysAsync(*pGateways, io, {addr1}); io.setNetworkInterfaces({addr1, addr2}); io.advanceTime(std::chrono::seconds(3)); expectGatewaysAsync(*pGateways, io, {addr1, addr2}); } TEST_CASE("PeerGateways | GatewayDisappears", "[PeerGateways]") { test::serial_io::Fixture io; io.setNetworkInterfaces({addr1, addr2}); auto pGateways = makePeerGateways( std::chrono::seconds(2), NodeState{}, Factory{}, util::injectVal(io.makeIoContext())); pGateways->enable(true); expectGatewaysAsync(*pGateways, io, {addr1, addr2}); io.setNetworkInterfaces({addr1}); io.advanceTime(std::chrono::seconds(3)); expectGatewaysAsync(*pGateways, io, {addr1}); } TEST_CASE("PeerGateways | GatewayChangesAddress", "[PeerGateways]") { test::serial_io::Fixture io; io.setNetworkInterfaces({addr1}); auto pGateways = makePeerGateways( std::chrono::seconds(2), NodeState{}, Factory{}, util::injectVal(io.makeIoContext())); pGateways->enable(true); expectGatewaysAsync(*pGateways, io, {addr1}); io.setNetworkInterfaces({addr2}); io.advanceTime(std::chrono::seconds(3)); expectGatewaysAsync(*pGateways, io, {addr2}); } } // namespace discovery } // namespace ableton link-Link-1.0.0/src/ableton/discovery/tst_PeerGateway.cpp0000644000175000017500000001271612765602651023650 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include namespace ableton { namespace discovery { namespace { struct TestNodeState : std::tuple { TestNodeState(std::string ident, double tempo) : std::tuple(std::move(ident), std::move(tempo)) { } std::string ident() const { return std::get<0>(*this); } }; struct TestMessenger { template void receive(Handler handler) { receivePeerState = [handler](const PeerState& msg) { handler(msg); }; receiveByeBye = [handler](const ByeBye& msg) { handler(msg); }; } std::function&)> receivePeerState; std::function&)> receiveByeBye; }; struct TestObserver { using GatewayObserverNodeState = TestNodeState; using GatewayObserverNodeId = std::string; friend void sawPeer(TestObserver& observer, const GatewayObserverNodeState& peer) { observer.mPeersSeen.push_back(peer); } friend void peerLeft(TestObserver& observer, const GatewayObserverNodeId& id) { observer.mPeersLeft.push_back(id); } friend void peerTimedOut(TestObserver& observer, const GatewayObserverNodeId& id) { observer.mPeersTimedOut.push_back(id); } std::vector mPeersSeen; std::vector mPeersLeft; std::vector mPeersTimedOut; }; void expectPeersSeen(std::vector expected, const TestObserver& observer) { CHECK(expected == observer.mPeersSeen); } void expectPeersLeft(std::vector expected, const TestObserver& observer) { CHECK(expected == observer.mPeersLeft); } void expectPeersTimedOut(std::vector expected, const TestObserver& observer) { CHECK(expected == observer.mPeersTimedOut); } // Test peers const auto peerA = TestNodeState{"peerA", 120}; const auto peerB = TestNodeState{"peerB", 150}; } // anonymous namespace TEST_CASE("PeerGateway | NoActivity", "[PeerGateway]") { test::serial_io::Fixture io; TestObserver observer; auto listener = makePeerGateway(util::injectVal(TestMessenger{}), util::injectRef(observer), util::injectVal(io.makeIoContext())); io.advanceTime(std::chrono::seconds(10)); // Without any outside interaction but the passage of time, our // listener should not have seen any peers. CHECK(observer.mPeersSeen.empty()); CHECK(observer.mPeersLeft.empty()); CHECK(observer.mPeersTimedOut.empty()); } TEST_CASE("PeerGateway | ReceivedPeerState", "[PeerGateway]") { test::serial_io::Fixture io; TestObserver observer; TestMessenger messenger; auto listener = makePeerGateway(util::injectRef(messenger), util::injectRef(observer), util::injectVal(io.makeIoContext())); messenger.receivePeerState({peerA, 5}); io.flush(); expectPeersSeen({peerA}, observer); } TEST_CASE("PeerGateway | TwoPeersOneLeaves", "[PeerGateway]") { test::serial_io::Fixture io; TestObserver observer; TestMessenger messenger; auto listener = makePeerGateway(util::injectRef(messenger), util::injectRef(observer), util::injectVal(io.makeIoContext())); messenger.receivePeerState({peerA, 5}); messenger.receivePeerState({peerB, 5}); messenger.receiveByeBye({peerA.ident()}); io.flush(); expectPeersSeen({peerA, peerB}, observer); expectPeersLeft({peerA.ident()}, observer); } TEST_CASE("PeerGateway | TwoPeersOneTimesOut", "[PeerGateway]") { test::serial_io::Fixture io; TestObserver observer; TestMessenger messenger; auto listener = makePeerGateway(util::injectRef(messenger), util::injectRef(observer), util::injectVal(io.makeIoContext())); messenger.receivePeerState({peerA, 5}); messenger.receivePeerState({peerB, 10}); io.advanceTime(std::chrono::seconds(3)); expectPeersTimedOut({}, observer); io.advanceTime(std::chrono::seconds(4)); expectPeersTimedOut({peerA.ident()}, observer); } TEST_CASE("PeerGateway | PeerTimesOutAndIsSeenAgain", "[PeerGateway]") { test::serial_io::Fixture io; TestObserver observer; TestMessenger messenger; auto listener = makePeerGateway(util::injectRef(messenger), util::injectRef(observer), util::injectVal(io.makeIoContext())); messenger.receivePeerState({peerA, 5}); io.advanceTime(std::chrono::seconds(7)); expectPeersTimedOut({peerA.ident()}, observer); messenger.receivePeerState({peerA, 5}); io.advanceTime(std::chrono::seconds(3)); expectPeersSeen({peerA, peerA}, observer); expectPeersTimedOut({peerA.ident()}, observer); } } // namespace discovery } // namespace ableton link-Link-1.0.0/src/ableton/discovery/tst_InterfaceScanner.cpp0000644000175000017500000000532512765602651024643 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include namespace ableton { namespace link { namespace { struct TestCallback { template void operator()(AddrRange addrs) { addrRanges.emplace_back(begin(addrs), end(addrs)); } std::vector> addrRanges; }; // some test addresses const asio::ip::address addr1 = asio::ip::address::from_string("123.123.123.1"); const asio::ip::address addr2 = asio::ip::address::from_string("123.123.123.2"); } // anonymous namespace TEST_CASE("InterfaceScanner | NoInterfacesThenOne", "[InterfaceScanner]") { test::serial_io::Fixture io; auto callback = TestCallback{}; { auto scanner = discovery::makeInterfaceScanner(std::chrono::seconds(2), util::injectRef(callback), util::injectVal(io.makeIoContext())); scanner.enable(true); CHECK(1 == callback.addrRanges.size()); io.setNetworkInterfaces({addr1}); io.advanceTime(std::chrono::seconds(3)); } REQUIRE(2 == callback.addrRanges.size()); CHECK(0 == callback.addrRanges[0].size()); REQUIRE(1 == callback.addrRanges[1].size()); CHECK(addr1 == callback.addrRanges[1].front()); } TEST_CASE("InterfaceScanner | InterfaceGoesAway", "[InterfaceScanner]") { test::serial_io::Fixture io; io.setNetworkInterfaces({addr1}); auto callback = TestCallback{}; { auto scanner = discovery::makeInterfaceScanner(std::chrono::seconds(2), util::injectRef(callback), util::injectVal(io.makeIoContext())); scanner.enable(true); io.setNetworkInterfaces({}); io.advanceTime(std::chrono::seconds(3)); } REQUIRE(2 == callback.addrRanges.size()); REQUIRE(1 == callback.addrRanges[0].size()); CHECK(addr1 == callback.addrRanges[0].front()); CHECK(0 == callback.addrRanges[1].size()); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/discovery/tst_Payload.cpp0000644000175000017500000001426212765602651023022 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include #include namespace ableton { namespace discovery { TEST_CASE("Payload | EmptyPayload", "[Payload]") { CHECK(0 == sizeInByteStream(makePayload())); CHECK(nullptr == toNetworkByteStream(makePayload(), nullptr)); } TEST_CASE("Payload | FixedSizeEntryPayloadSize", "[Payload]") { CHECK(12 == sizeInByteStream(makePayload(test::Foo{}))); } TEST_CASE("Payload | SingleEntryPayloadEncoding", "[Payload]") { const auto payload = makePayload(test::Foo{-1}); std::vector bytes(sizeInByteStream(payload)); const auto end = toNetworkByteStream(payload, begin(bytes)); // Should have filled the buffer with the payload CHECK(bytes.size() == static_cast(end - begin(bytes))); // Should have encoded the value 1 after the payload entry header // as an unsigned in network byte order const auto uresult = ntohl(reinterpret_cast(*(begin(bytes) + 8))); CHECK(-1 == reinterpret_cast(uresult)); } TEST_CASE("Payload | DoubleEntryPayloadSize", "[Payload]") { CHECK(44 == sizeInByteStream(makePayload(test::Foo{}, test::Bar{{0, 1, 2}}))); } TEST_CASE("Payload | DoubleEntryPayloadEncoding", "[Payload]") { const auto payload = makePayload(test::Foo{1}, test::Bar{{0, 1, 2}}); std::vector bytes(sizeInByteStream(payload)); const auto end = toNetworkByteStream(payload, begin(bytes)); // Should have filled the buffer with the payload CHECK(bytes.size() == static_cast(end - begin(bytes))); // Should have encoded the value 1 after the first payload entry header // and 0,1,2 after the second payload entry header in network byte // order CHECK(1 == ntohl(reinterpret_cast(*(begin(bytes) + 8)))); CHECK(0 == ntohll(reinterpret_cast(*(begin(bytes) + 20)))); CHECK(1 == ntohll(reinterpret_cast(*(begin(bytes) + 28)))); CHECK(2 == ntohll(reinterpret_cast(*(begin(bytes) + 36)))); } TEST_CASE("Payload | RoundtripSingleEntry", "[Payload]") { const auto expected = test::Foo{1}; const auto payload = makePayload(expected); std::vector bytes(sizeInByteStream(payload)); const auto end = toNetworkByteStream(payload, begin(bytes)); test::Foo actual{}; parsePayload( begin(bytes), end, [&actual](const test::Foo& foo) { actual = foo; }); CHECK(expected.fooVal == actual.fooVal); } TEST_CASE("Payload | RoundtripDoubleEntry", "[Payload]") { const auto expectedFoo = test::Foo{1}; const auto expectedBar = test::Bar{{0, 1, 2}}; const auto payload = makePayload(expectedBar, expectedFoo); std::vector bytes(sizeInByteStream(payload)); const auto end = toNetworkByteStream(payload, begin(bytes)); test::Foo actualFoo{}; test::Bar actualBar{}; parsePayload(begin(bytes), end, [&actualFoo](const test::Foo& foo) { actualFoo = foo; }, [&actualBar](const test::Bar& bar) { actualBar = bar; }); CHECK(expectedFoo.fooVal == actualFoo.fooVal); CHECK(expectedBar.barVals == actualBar.barVals); } TEST_CASE("Payload | ParseSubset", "[Payload]") { // Encode two payload entries const auto expectedFoo = test::Foo{1}; const auto expectedBar = test::Bar{{0, 1, 2}}; const auto payload = makePayload(expectedFoo, expectedBar); std::vector bytes(sizeInByteStream(payload)); const auto end = toNetworkByteStream(payload, begin(bytes)); // Only decode one of them test::Bar actualBar{}; parsePayload( begin(bytes), end, [&actualBar](const test::Bar& bar) { actualBar = bar; }); CHECK(expectedBar.barVals == actualBar.barVals); } TEST_CASE("Payload | ParseTruncatedEntry", "[Payload]") { const auto expectedFoo = test::Foo{1}; const auto expectedBar = test::Bar{{0, 1, 2}}; const auto payload = makePayload(expectedBar, expectedFoo); std::vector bytes(sizeInByteStream(payload)); const auto end = toNetworkByteStream(payload, begin(bytes)); test::Foo actualFoo{}; test::Bar actualBar{}; REQUIRE_THROWS_AS(( // We truncate the buffer by one byte parsePayload(begin(bytes), end - 1, [&actualFoo](const test::Foo& foo) { actualFoo = foo; }, [&actualBar](const test::Bar& bar) { actualBar = bar; })), std::runtime_error); // We expect that bar should be properly parsed but foo not CHECK(0 == actualFoo.fooVal); CHECK(expectedBar.barVals == actualBar.barVals); } TEST_CASE("Payload | AddPayloads", "[Payload]") { // The sum of a foo payload and a bar payload should be equal in // every way to a foobar payload const auto foo = test::Foo{1}; const auto bar = test::Bar{{0, 1, 2}}; const auto fooBarPayload = makePayload(foo, bar); const auto sumPayload = makePayload(foo) + makePayload(bar); REQUIRE(sizeInByteStream(fooBarPayload) == sizeInByteStream(sumPayload)); std::vector fooBarBytes(sizeInByteStream(fooBarPayload)); std::vector sumBytes(sizeInByteStream(sumPayload)); const auto fooBarEnd = toNetworkByteStream(fooBarPayload, begin(fooBarBytes)); toNetworkByteStream(sumPayload, begin(sumBytes)); CHECK(std::equal(begin(fooBarBytes), fooBarEnd, begin(sumBytes))); } } // namespace discovery } // namespace ableton link-Link-1.0.0/src/ableton/link/0000755000175000017500000000000012765602651016754 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/ableton/link/tst_PingResponder.cpp0000644000175000017500000001042312765602651023131 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include #include #include #include #include #include #include #include #include #include namespace ableton { namespace link { namespace { struct RpFixture { RpFixture() : mAddress(asio::ip::address_v4::from_string("127.0.0.1")) , mResponder(mAddress, NodeId::random(), GhostXForm{1.0, std::chrono::microseconds{0}}, util::injectVal(util::test::IoService{}), MockClock{}, util::injectVal(util::NullLog{})) { } discovery::test::Socket responderSocket() { return mResponder.socket(); } std::size_t numSentMessages() { return responderSocket().sentMessages.size(); } struct MockClock { std::chrono::microseconds micros() const { return std::chrono::microseconds{4}; } }; asio::ip::address_v4 mAddress = asio::ip::address_v4::from_string("127.0.0.1"); PingResponder mResponder; }; } // anonymous namespace TEST_CASE("PingResponder | ReplyToPing", "[PingResponder]") { using std::chrono::microseconds; RpFixture fixture; // Construct and send Ping Message. Check if Responder sent back a Message const auto payload = discovery::makePayload(HostTime{microseconds(2)}, PrevGHostTime{microseconds(1)}); v1::MessageBuffer buffer; const auto msgBegin = std::begin(buffer); const auto msgEnd = v1::pingMessage(payload, msgBegin); const auto endpoint = asio::ip::udp::endpoint(fixture.mAddress, 8888); fixture.responderSocket().incomingMessage(endpoint, msgBegin, msgEnd); CHECK(1 == fixture.numSentMessages()); // Check Responder's message const auto messageBuffer = fixture.responderSocket().sentMessages[0].first; const auto result = v1::parseMessageHeader(begin(messageBuffer), end(messageBuffer)); const auto& hdr = result.first; std::chrono::microseconds ghostTime{0}; std::chrono::microseconds prevGHostTime{0}; std::chrono::microseconds hostTime{0}; discovery::parsePayload(result.second, std::end(messageBuffer), [&ghostTime](GHostTime gt) { ghostTime = std::move(gt.time); }, [&prevGHostTime](PrevGHostTime gt) { prevGHostTime = std::move(gt.time); }, [&hostTime](HostTime ht) { hostTime = std::move(ht.time); }); CHECK(v1::kPong == hdr.messageType); CHECK(std::chrono::microseconds{2} == hostTime); CHECK(std::chrono::microseconds{1} == prevGHostTime); CHECK(std::chrono::microseconds{4} == ghostTime); } TEST_CASE("PingResponder | PingSizeExceeding", "[PingResponder]") { using std::chrono::microseconds; RpFixture fixture; const auto ht = HostTime{microseconds(2)}; const auto payload = discovery::makePayload(ht, ht, ht); v1::MessageBuffer buffer; const auto msgBegin = std::begin(buffer); const auto msgEnd = v1::pingMessage(payload, msgBegin); const auto endpoint = asio::ip::udp::endpoint(fixture.mAddress, 8888); fixture.responderSocket().incomingMessage(endpoint, msgBegin, msgEnd); CHECK(0 == fixture.numSentMessages()); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_HostTimeFilter.cpp0000644000175000017500000000410012765602651023247 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include namespace ableton { namespace link { struct MockClock { MockClock() : time(std::chrono::microseconds(0)) { } std::chrono::microseconds micros() { const auto current = time; time += std::chrono::microseconds(1); return current; } std::chrono::microseconds time; }; using Filter = ableton::link::HostTimeFilter; TEST_CASE("HostTimeFilter | OneValue", "[HostTimeFilter]") { Filter filter; const auto ht = filter.sampleTimeToHostTime(5); CHECK(0 == ht.count()); } TEST_CASE("HostTimeFilter | MultipleValues", "[HostTimeFilter]") { Filter filter; const auto numValues = 600; auto ht = std::chrono::microseconds(0); for (int i = 0; i <= numValues; ++i) { ht = filter.sampleTimeToHostTime(i); } CHECK(numValues == ht.count()); } TEST_CASE("HostTimeFilter | Reset", "[HostTimeFilter]") { Filter filter; auto ht = filter.sampleTimeToHostTime(0); ht = filter.sampleTimeToHostTime(-230); ht = filter.sampleTimeToHostTime(40); REQUIRE(2 != ht.count()); filter.reset(); ht = filter.sampleTimeToHostTime(0); CHECK(3 == ht.count()); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_ClientSessionTimelines.cpp0000644000175000017500000001356512765602651025020 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include namespace ableton { namespace link { namespace { using std::chrono::microseconds; // Make the constants non-zero to make sure we're not hiding bugs const auto b0 = Beats{-1.}; const auto t0 = microseconds{-1}; const auto xform = GhostXForm{1., microseconds{-1000000}}; } TEST_CASE("session->client | UpdatesTempo", "[ClientSessionTimelines]") { const auto curClient = Timeline{Tempo{60.}, b0, t0}; const auto session = Timeline{Tempo{90.}, b0, xform.hostToGhost(t0)}; const auto newClient = updateClientTimelineFromSession(curClient, session, t0, xform); CHECK(newClient.tempo == Tempo{90.}); } TEST_CASE("session->client | PreservesClientBeatMagnitude", "[ClientSessionTimelines]") { const auto curClient = Timeline{Tempo{60.}, b0, t0}; const auto session = Timeline{Tempo{120.}, Beats{12.32}, microseconds{-123456789}}; // Transition to the session timeline at t1 const auto t1 = t0 + microseconds{5000000}; const auto b1 = curClient.toBeats(t1); const auto newClient = updateClientTimelineFromSession(curClient, session, t1, xform); // The new client timeline should have the same magnitude as the old // one at the transition point CHECK(newClient.toBeats(t1) == b1); // At t1 + dt, the new tempo should be in effect CHECK(newClient.toBeats(t1 + microseconds{1000000}) == b1 + Beats{2.}); } TEST_CASE("session->client | AtDifferentTimesGivesSameResult", "[ClientSessionTimelines]") { const auto curClient = Timeline{Tempo{60.}, b0, t0}; const auto session = Timeline{Tempo{120.}, Beats{-11.}, microseconds{-12356789}}; const auto t1 = t0 + microseconds{5000000}; const auto t2 = t1 + microseconds{6849353}; // Once a given session timeline has been converted to a client // timeline, converting again from the same session at different // times should not change the result because the result is colinear // and the origin should always be anchored at the session's beat 0. const auto updated1 = updateClientTimelineFromSession(curClient, session, t1, xform); const auto updated2 = updateClientTimelineFromSession(updated1, session, t2, xform); CHECK(updated1 == updated2); } TEST_CASE("session->client | EncodesSessionOrigin", "[ClientSessionTimelines]") { const auto curClient = Timeline{Tempo{60.}, b0, t0}; const auto session = Timeline{Tempo{21.3}, Beats{-421.3}, microseconds{15003240}}; const auto newClient = updateClientTimelineFromSession(curClient, session, microseconds{-1345298}, xform); // The new client timeline's origin should be at beat 0 on the // session timeline. This is how we encode the session origin in the // client timeline. CHECK(xform.hostToGhost(newClient.timeOrigin) == session.fromBeats(Beats{0.})); } TEST_CASE("client->session | ShiftedForward", "[ClientSessionTimeline]") { const auto session = Timeline{Tempo{60.}, b0, t0}; auto client = Timeline{Tempo{60.}, Beats{111.}, xform.ghostToHost(t0)}; client = updateClientTimelineFromSession(client, session, t0, xform); // Shift the phase one beat forward client = shiftClientTimeline(client, Beats{1.}); const auto newSession = updateSessionTimelineFromClient(session, client, xform.ghostToHost(t0), xform); CHECK(newSession.toBeats(t0) == b0 + Beats{1.}); } TEST_CASE("client->session | ShiftedBackward", "[ClientSessionTimeline]") { const auto session = Timeline{Tempo{60.}, b0, t0}; auto client = Timeline{Tempo{60.}, Beats{983.}, xform.ghostToHost(t0)}; client = updateClientTimelineFromSession(client, session, t0, xform); // Shift the phase one beat backward client = shiftClientTimeline(client, Beats{-1.}); const auto newSession = updateSessionTimelineFromClient(session, client, xform.ghostToHost(t0), xform); CHECK(newSession.toBeats(t0) == b0 - Beats{1.}); } TEST_CASE("session->client->session | Roundtrip", "[ClientSessionTimeline]") { const auto session = Timeline{Tempo{60.}, b0, t0}; // Initial client timeline values shouldn't matter auto client = Timeline{Tempo{213.5}, Beats{432.}, microseconds{5143503}}; client = updateClientTimelineFromSession(client, session, t0, xform); auto newSession = updateSessionTimelineFromClient(session, client, microseconds{42905944}, xform); CHECK(session == newSession); // Now verify that modifying the client timeline and then routing it // through a session update results in the same client timeline. const auto updateTime = microseconds{-35023900}; newSession = updateSessionTimelineFromClient(newSession, client, updateTime, xform); const auto newClient = updateClientTimelineFromSession(client, newSession, updateTime, xform); CHECK(client == newClient); } TEST_CASE("shiftClientTimelineOrigin | Shift", "[ClientSessionTimeline]") { const auto shift = Beats{1.1}; const auto timeline = Timeline{Tempo{60.}, b0, t0}; CHECK(shiftClientTimeline(timeline, shift).toBeats(t0) == timeline.toBeats(t0) + shift); CHECK( shiftClientTimeline(timeline, -shift).toBeats(t0) == timeline.toBeats(t0) - shift); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_LinearRegression.cpp0000644000175000017500000000436512765602651023635 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include namespace ableton { namespace link { using Vector = std::vector>; TEST_CASE("LinearRegression | EmptyVector", "[LinearRegression]") { Vector data; const auto result = linearRegression(data.begin(), data.end()); CHECK(0 == Approx(result.first)); } TEST_CASE("LinearRegression | OnePoint", "[LinearRegression]") { using Array = std::array, 1>; Array data; data[0] = {}; const auto result = linearRegression(data.begin(), data.end()); CHECK(0 == Approx(result.first)); CHECK(0 == Approx(result.second)); } TEST_CASE("LinearRegression | TwoPoints", "[LinearRegression]") { Vector data; data.emplace_back(0.0, 0.0); data.emplace_back(666666.6, 66666.6); const auto result = linearRegression(data.begin(), data.end()); CHECK(0.1 == Approx(result.first)); CHECK(0.0 == Approx(result.second)); } TEST_CASE("LinearRegression | 10000Points", "[LinearRegression]") { Vector data; const double slope = -0.2; const double intercept = -357.53456; for (int i = 1; i < 10000; ++i) { data.emplace_back(i, i * slope + intercept); } const auto result = linearRegression(data.begin(), data.end()); CHECK(slope == Approx(result.first)); CHECK(intercept == Approx(result.second)); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Peers.cpp0000644000175000017500000001341412765602651021433 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include namespace ableton { namespace link { namespace { struct SessionMembershipCallback { void operator()() { ++calls; } std::size_t calls = 0; }; struct SessionTimelineCallback { void operator()(const SessionId& session, const Timeline& tl) { sessionTimelines.push_back(std::make_pair(session, tl)); } std::vector> sessionTimelines; }; const auto fooPeer = PeerState{{NodeId::random(), NodeId::random(), Timeline{Tempo{60.}, Beats{1.}, std::chrono::microseconds{1234}}}, {}}; const auto barPeer = PeerState{{NodeId::random(), NodeId::random(), Timeline{Tempo{120.}, Beats{10.}, std::chrono::microseconds{500}}}, {}}; const auto bazPeer = PeerState{{NodeId::random(), NodeId::random(), Timeline{Tempo{100.}, Beats{4.}, std::chrono::microseconds{100}}}, {}}; const auto gateway1 = asio::ip::address::from_string("123.123.123.123"); const auto gateway2 = asio::ip::address::from_string("210.210.210.210"); using PeerVector = std::vector::Peer>; void expectPeers(PeerVector expected, PeerVector actual) { CHECK(expected == actual); } void expectSessionTimelines( std::vector> expected, SessionTimelineCallback callback) { CHECK(expected == callback.sessionTimelines); } } // anonymous namespace TEST_CASE("Peers | EmptySessionPeersAfterInit", "[Peers]") { test::serial_io::Fixture io; auto peers = makePeers(util::injectVal(io.makeIoContext()), SessionMembershipCallback{}, SessionTimelineCallback{}); io.flush(); expectPeers({}, peers.sessionPeers(fooPeer.sessionId())); } TEST_CASE("Peers | AddAndFindPeer", "[Peers]") { test::serial_io::Fixture io; auto membership = SessionMembershipCallback{}; auto sessions = SessionTimelineCallback{}; auto peers = makePeers( util::injectVal(io.makeIoContext()), std::ref(membership), std::ref(sessions)); auto observer = makeGatewayObserver(peers, gateway1); sawPeer(observer, fooPeer); io.flush(); expectPeers({{fooPeer, gateway1}}, peers.sessionPeers(fooPeer.sessionId())); CHECK(1u == membership.calls); expectSessionTimelines({make_pair(fooPeer.sessionId(), fooPeer.timeline())}, sessions); } TEST_CASE("Peers | AddAndRemovePeer", "[Peers]") { test::serial_io::Fixture io; auto membership = SessionMembershipCallback{}; auto peers = makePeers( util::injectVal(io.makeIoContext()), std::ref(membership), SessionTimelineCallback{}); auto observer = makeGatewayObserver(peers, gateway1); sawPeer(observer, fooPeer); peerLeft(observer, fooPeer.ident()); io.flush(); expectPeers({}, peers.sessionPeers(fooPeer.sessionId())); CHECK(2u == membership.calls); } TEST_CASE("Peers | AddTwoPeersRemoveOne", "[Peers]") { test::serial_io::Fixture io; auto membership = SessionMembershipCallback{}; auto sessions = SessionTimelineCallback{}; auto peers = makePeers( util::injectVal(io.makeIoContext()), std::ref(membership), std::ref(sessions)); auto observer = makeGatewayObserver(peers, gateway1); sawPeer(observer, fooPeer); sawPeer(observer, barPeer); peerLeft(observer, fooPeer.ident()); io.flush(); expectPeers({}, peers.sessionPeers(fooPeer.sessionId())); expectPeers({{barPeer, gateway1}}, peers.sessionPeers(barPeer.sessionId())); CHECK(3u == membership.calls); } TEST_CASE("Peers | AddThreePeersTwoOnSameGateway", "[Peers]") { test::serial_io::Fixture io; auto membership = SessionMembershipCallback{}; auto sessions = SessionTimelineCallback{}; auto peers = makePeers( util::injectVal(io.makeIoContext()), std::ref(membership), std::ref(sessions)); auto observer1 = makeGatewayObserver(peers, gateway1); auto observer2 = makeGatewayObserver(peers, gateway2); sawPeer(observer1, fooPeer); sawPeer(observer2, fooPeer); sawPeer(observer1, barPeer); sawPeer(observer1, bazPeer); io.flush(); expectPeers( {{fooPeer, gateway1}, {fooPeer, gateway2}}, peers.sessionPeers(fooPeer.sessionId())); CHECK(3 == membership.calls); } TEST_CASE("Peers | CloseGateway", "[Peers]") { test::serial_io::Fixture io; auto membership = SessionMembershipCallback{}; auto sessions = SessionTimelineCallback{}; auto peers = makePeers( util::injectVal(io.makeIoContext()), std::ref(membership), std::ref(sessions)); auto observer1 = makeGatewayObserver(peers, gateway1); { // The observer will close the gateway when it goes out of scope auto observer2 = makeGatewayObserver(peers, gateway2); sawPeer(observer2, fooPeer); sawPeer(observer2, barPeer); sawPeer(observer1, fooPeer); sawPeer(observer2, bazPeer); } io.flush(); expectPeers({{fooPeer, gateway1}}, peers.sessionPeers(fooPeer.sessionId())); CHECK(4 == membership.calls); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Controller.cpp0000644000175000017500000000721412765602651022501 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include namespace ableton { namespace link { using namespace std::chrono; namespace { struct MockClock { using Ticks = std::int64_t; Ticks ticks() const { return 1; } microseconds micros() const { return microseconds{1}; } }; struct MockIoContext { template struct Socket { std::size_t send( const uint8_t* const, const size_t numBytes, const asio::ip::udp::endpoint&) { return numBytes; } template void receive(Handler) { } asio::ip::udp::endpoint endpoint() const { return {}; } }; template Socket openUnicastSocket(const asio::ip::address_v4&) { return {}; } template Socket openMulticastSocket(const asio::ip::address_v4&) { return {}; } std::vector scanNetworkInterfaces() { return {}; } using Timer = util::test::Timer; Timer makeTimer() { return {}; } using Log = util::NullLog; Log log() const { return {}; } template void async(Handler handler) const { handler(); } MockIoContext clone() const { return {}; } template MockIoContext clone(ExceptionHandler) const { return {}; } template struct RealTimeContext { RealTimeContext(util::Injected io) : mIo(std::move(io)) { } template void async(Handler handler) const { mIo->async(std::move(handler)); } util::Injected mIo; }; }; using MockController = Controller; } // anon namespace TEST_CASE("Controller | ConstructOptimistically", "[Controller]") { MockController controller(Tempo{100.0}, [](std::size_t) {}, [](Tempo) {}, MockClock{}, util::injectVal(MockIoContext{})); CHECK(!controller.isEnabled()); CHECK(0 == controller.numPeers()); const auto tl = controller.timeline(); CHECK(Tempo{100.0} == tl.tempo); } TEST_CASE("Controller | ConstructWithInvalidTempo", "[Controller]") { MockController controllerLowTempo(Tempo{1.0}, [](std::size_t) {}, [](Tempo) {}, MockClock{}, util::injectVal(MockIoContext{})); const auto tlLow = controllerLowTempo.timeline(); CHECK(Tempo{20.0} == tlLow.tempo); MockController controllerHighTempo(Tempo{100000.0}, [](std::size_t) {}, [](Tempo) {}, MockClock{}, util::injectVal(MockIoContext{})); const auto tlHigh = controllerHighTempo.timeline(); CHECK(Tempo{999.0} == tlHigh.tempo); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Kalman.cpp0000644000175000017500000000322112765602651021553 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include namespace ableton { namespace link { TEST_CASE("Kalman | Check1", "[Kalman]") { int peerTimeDiff = 0; Kalman<16> filter; for (int i = 0; i < 5; ++i) { filter.iterate(peerTimeDiff); } CHECK(peerTimeDiff == Approx(filter.getValue())); filter.iterate(100); CHECK(peerTimeDiff != Approx(filter.getValue())); } TEST_CASE("Kalman | Check2", "[Kalman]") { double peerTimeDiff = 3e11; Kalman<5> filter; for (int i = 0; i < 15; ++i) { filter.iterate(peerTimeDiff); } CHECK(peerTimeDiff == Approx(filter.getValue())); for (int i = 0; i < 15; ++i) { filter.iterate(11); } CHECK(peerTimeDiff != Approx(filter.getValue())); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Tempo.cpp0000644000175000017500000000571312765602651021444 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include namespace ableton { namespace link { TEST_CASE("Tempo | ConstructFromBpm", "[Tempo]") { const auto tempo = Tempo{120.}; CHECK(120. == Approx(tempo.bpm())); CHECK(std::chrono::microseconds{500000} == tempo.microsPerBeat()); } TEST_CASE("Tempo | ConstructFromMicros", "[Tempo]") { const auto tempo = Tempo{std::chrono::microseconds{500000}}; CHECK(120. == Approx(tempo.bpm())); CHECK(std::chrono::microseconds{500000} == tempo.microsPerBeat()); } TEST_CASE("Tempo | MicrosToBeats", "[Tempo]") { const auto tempo = Tempo{120.}; CHECK(Beats{2.} == tempo.microsToBeats(std::chrono::microseconds{1000000})); } TEST_CASE("Tempo | BeatsToMicros", "[Tempo]") { const auto tempo = Tempo{120.}; CHECK(std::chrono::microseconds{1000000} == tempo.beatsToMicros(Beats{2.})); } TEST_CASE("Tempo | ComparisonLT", "[Tempo]") { const auto tempo1 = Tempo{100.}; const auto tempo2 = Tempo{200.}; CHECK(tempo1 < tempo2); } TEST_CASE("Tempo | ComparisonGT", "[Tempo]") { const auto tempo1 = Tempo{100.}; const auto tempo2 = Tempo{200.}; CHECK(tempo2 > tempo1); } TEST_CASE("Tempo | ComparisonLE", "[Tempo]") { const auto tempo1 = Tempo{100.}; const auto tempo2 = Tempo{200.}; CHECK(tempo1 <= tempo2); CHECK(tempo2 <= tempo2); } TEST_CASE("Tempo | ComparisonGE", "[Tempo]") { const auto tempo1 = Tempo{100.}; const auto tempo2 = Tempo{200.}; CHECK(tempo2 >= tempo1); CHECK(tempo2 >= tempo2); } TEST_CASE("Tempo | ComparisonEQ", "[Tempo]") { const auto tempo1 = Tempo{100.}; const auto tempo2 = Tempo{100.}; CHECK(tempo1 == tempo2); } TEST_CASE("Tempo | ComparisonNE", "[Tempo]") { const auto tempo1 = Tempo{100.}; const auto tempo2 = Tempo{200.}; CHECK(tempo1 != tempo2); } TEST_CASE("Tempo | RoundtripByteStreamEncoding", "[Tempo]") { const auto tempo = Tempo{120.}; std::vector bytes(sizeInByteStream(tempo)); const auto end = toNetworkByteStream(tempo, begin(bytes)); const auto result = Tempo::fromNetworkByteStream(begin(bytes), end); CHECK(tempo == result.first); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Beats.cpp0000644000175000017500000000503012765602651021406 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include namespace ableton { namespace link { TEST_CASE("Beats | ConstructFromFloating", "[Beats]") { const auto beats = Beats{0.5}; CHECK(500000 == beats.microBeats()); CHECK(0.5 == Approx(beats.floating())); } TEST_CASE("Beats | ConstructFromMicros", "[Beats]") { const auto beats = Beats{INT64_C(100000)}; CHECK(100000 == beats.microBeats()); CHECK(0.1 == Approx(beats.floating())); } TEST_CASE("Beats | Negation", "[Beats]") { const auto beat = Beats{1.}; CHECK(beat > -beat); CHECK(beat == -(-beat)); CHECK(-beat < Beats{0.}); } TEST_CASE("Beats | Addition", "[Beats]") { const auto beat1 = Beats{0.5}; const auto beat2 = Beats{INT64_C(200000)}; const auto beat3 = Beats{0.1}; CHECK(beat1 == beat2 + beat2 + beat3); } TEST_CASE("Beats | Subtraction", "[Beats]") { const auto beat1 = Beats{0.5}; const auto beat2 = Beats{INT64_C(200000)}; const auto beat3 = Beats{0.1}; CHECK(beat3 == beat1 - beat2 - beat2); } TEST_CASE("Beats | Modulo", "[Beats]") { const auto beat1 = Beats{0.1}; const auto beat2 = Beats{0.5}; const auto beat3 = Beats{0.6}; const auto beat4 = Beats{0.}; CHECK(beat1 == beat3 % beat2); CHECK(beat4 == beat3 % beat4); } TEST_CASE("Beats | SizeInByteStream", "[Beats]") { Beats beats{0.5}; CHECK(8 == sizeInByteStream(beats)); } TEST_CASE("Beats | RoundtripByteStreamEncoding", "[Beats]") { Beats beats{0.5}; std::vector bytes(sizeInByteStream(beats)); const auto end = toNetworkByteStream(beats, begin(bytes)); const auto result = Beats::fromNetworkByteStream(begin(bytes), end); CHECK(beats == result.first); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Timeline.cpp0000644000175000017500000000343712765602651022127 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include namespace ableton { namespace link { TEST_CASE("Timeline | TimeToBeats", "[Timeline]") { const auto tl = Timeline{Tempo{60.}, Beats{-1.}, std::chrono::microseconds{1000000}}; CHECK(Beats{2.5} == tl.toBeats(std::chrono::microseconds{4500000})); } TEST_CASE("Timeline | BeatsToTime", "[Timeline]") { const auto tl = Timeline{Tempo{60.}, Beats{-1.}, std::chrono::microseconds{1000000}}; CHECK(std::chrono::microseconds{5200000} == tl.fromBeats(Beats{3.2})); } TEST_CASE("Timeline | RoundtripByteStreamEncoding", "[Timeline]") { const auto tl = Timeline{Tempo{120.}, Beats{5.5}, std::chrono::microseconds{12558940}}; std::vector bytes(sizeInByteStream(tl)); const auto end = toNetworkByteStream(tl, begin(bytes)); const auto result = Timeline::fromNetworkByteStream(begin(bytes), end); CHECK(tl == result.first); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Measurement.cpp0000644000175000017500000001137212765602651022643 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include #include #include #include #include #include #include #include #include namespace ableton { namespace link { namespace { using Socket = discovery::test::Socket; struct MockClock { std::chrono::microseconds micros() const { return std::chrono::microseconds{4}; } }; struct TFixture { TFixture() : mAddress(asio::ip::address_v4::from_string("127.0.0.1")) , mMeasurement(mStateQuery(), [](std::vector>) {}, mAddress, MockClock{}, util::injectVal(util::NullLog{})) { } Socket& socket() { return *(mMeasurement.mpImpl->mpSocket); } struct StateQuery { StateQuery() { mState.nodeState.sessionId = NodeId::random(); mState.endpoint = asio::ip::udp::endpoint(asio::ip::address_v4::from_string("127.0.0.1"), 9999); } PeerState operator()() { return mState; } PeerState mState; }; struct GhostXFormQuery { GhostXForm operator()() const { return {1.0, std::chrono::microseconds{0}}; } }; StateQuery mStateQuery; GhostXFormQuery mGhostXFormQuery; asio::ip::address_v4 mAddress; Measurement mMeasurement; }; } // anonymous namespace TEST_CASE("Measurement | SendPingsOnConstruction", "[Measurement]") { TFixture fixture; CHECK(1 == fixture.socket().sentMessages.size()); const auto messageBuffer = fixture.socket().sentMessages[0].first; const auto result = v1::parseMessageHeader(std::begin(messageBuffer), std::end(messageBuffer)); const auto& header = result.first; std::chrono::microseconds gt{0}; std::chrono::microseconds ht{0}; discovery::parsePayload(result.second, std::end(messageBuffer), [>](GHostTime ghostTime) { gt = std::move(ghostTime.time); }, [&ht](HostTime hostTime) { ht = std::move(hostTime.time); }); CHECK(v1::kPing == header.messageType); CHECK(std::chrono::microseconds{4} == ht); CHECK(std::chrono::microseconds{0} == gt); } TEST_CASE("Measurement | ReceiveInitPong", "[Measurement]") { using Micros = std::chrono::microseconds; TFixture fixture; const auto id = SessionMembership{fixture.mStateQuery.mState.nodeState.sessionId}; const auto ht = HostTime{Micros(0)}; const auto gt = GHostTime{Micros(0)}; const auto payload = discovery::makePayload(id, gt, ht); v1::MessageBuffer buffer; const auto msgBegin = std::begin(buffer); const auto msgEnd = v1::pongMessage(payload, msgBegin); const auto endpoint = asio::ip::udp::endpoint(asio::ip::address_v4::from_string("127.0.0.1"), 8888); fixture.socket().incomingMessage(endpoint, msgBegin, msgEnd); CHECK(2 == fixture.socket().sentMessages.size()); CHECK(0 == fixture.mMeasurement.mpImpl->mData.size()); } TEST_CASE("Measurement | ReceivePong", "[Measurement]") { using Micros = std::chrono::microseconds; TFixture fixture; const auto id = SessionMembership{fixture.mStateQuery.mState.nodeState.sessionId}; const auto ht = HostTime{Micros(2)}; const auto gt = GHostTime{Micros(3)}; const auto pgt = PrevGHostTime{Micros(1)}; const auto payload = discovery::makePayload(id, gt, ht, pgt); v1::MessageBuffer buffer; const auto msgBegin = std::begin(buffer); const auto msgEnd = v1::pongMessage(payload, msgBegin); const auto endpoint = asio::ip::udp::endpoint(asio::ip::address_v4::from_string("127.0.0.1"), 8888); fixture.socket().incomingMessage(endpoint, msgBegin, msgEnd); CHECK(2 == fixture.socket().sentMessages.size()); CHECK(2 == fixture.mMeasurement.mpImpl->mData.size()); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/link/tst_Phase.cpp0000644000175000017500000001474612765602651021426 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include namespace ableton { namespace link { namespace { const auto zero = Beats{0.}; const auto one = Beats{1.}; const auto two = Beats{2.}; const auto three = Beats{3.}; const auto four = Beats{4.}; using std::chrono::microseconds; const auto tl0 = Timeline{Tempo{120.}, one, microseconds{0}}; const auto tl1 = Timeline{Tempo{60.}, Beats{-9.5}, microseconds{2000000}}; } TEST_CASE("phase | phase(x, 0) == 0", "[Phase]") { CHECK(phase(zero, zero) == zero); CHECK(phase(Beats{0.1}, zero) == zero); CHECK(phase(one, zero) == zero); CHECK(phase(-one, zero) == zero); } TEST_CASE("phase | phase(x, y) == x % y when x and y >= 0", "[Phase]") { CHECK(phase(zero, zero) == zero % zero); CHECK(phase(one, zero) == one % zero); CHECK(phase(zero, one) == zero % one); CHECK(phase(Beats{0.1}, one) == Beats{0.1} % one); CHECK(phase(Beats{2.3}, one) == Beats{2.3} % one); CHECK(phase(Beats{9.5}, Beats{2.3}) == Beats{9.5} % Beats{2.3}); } TEST_CASE("phase | phase of negatives is not mirrored around zero", "[Phase]") { CHECK(phase(-one, one) == zero); CHECK(phase(Beats{-0.1}, one) == Beats{0.9}); CHECK(phase(Beats{-2.3}, one) == Beats{0.7}); CHECK(phase(Beats{-9.5}, Beats{2.3}) == Beats{2.}); } TEST_CASE("nextPhaseMatch | result == x when quantum == 0", "[Phase]") { CHECK(nextPhaseMatch(Beats{0.1}, one, zero) == Beats{0.1}); CHECK(nextPhaseMatch(Beats{2.3}, Beats{9.5}, zero) == Beats{2.3}); CHECK(nextPhaseMatch(Beats{-0.1}, Beats{-2.3}, zero) == Beats{-0.1}); } TEST_CASE("nextPhaseMatch | result == target when 0 <= x < target < quantum", "[Phase]") { CHECK(nextPhaseMatch(zero, Beats{0.1}, one) == Beats{0.1}); CHECK(nextPhaseMatch(Beats{0.1}, one, two) == one); CHECK(nextPhaseMatch(one, two, Beats{2.3}) == two); CHECK(nextPhaseMatch(two, Beats{2.3}, three) == Beats{2.3}); } TEST_CASE("nextPhaseMatch | some example cases", "[Phase]") { CHECK(nextPhaseMatch(one, Beats{2.3}, two) == Beats{2.3}); CHECK(nextPhaseMatch(Beats{2.3}, Beats{-0.1}, two) == Beats{3.9}); CHECK(nextPhaseMatch(Beats{-9.5}, Beats{0.1}, two) == Beats{-7.9}); CHECK(nextPhaseMatch(Beats{-2.3}, Beats{0.1}, Beats{9.5}) == Beats{0.1}); } TEST_CASE("toPhaseEncodedBeats | result == tl.toBeats when quantum == 0", "[Phase]") { const auto t0 = microseconds{0}; const auto t1 = microseconds{2000000}; const auto t2 = microseconds{-3200000}; CHECK(toPhaseEncodedBeats(tl1, t0, zero) == tl1.toBeats(t0)); CHECK(toPhaseEncodedBeats(tl0, t1, zero) == tl0.toBeats(t1)); CHECK(toPhaseEncodedBeats(tl0, t2, zero) == tl0.toBeats(t2)); } TEST_CASE("toPhaseEncodedBeats | result is the nearest quantum boundary", "[Phase]") { const auto sec = microseconds{1000000}; // Takes the previous boundary CHECK(toPhaseEncodedBeats(tl0, sec, Beats{2.2}) == two); // Takes the next boundary CHECK(toPhaseEncodedBeats(tl0, sec, Beats{1.8}) == Beats{3.8}); // Takes the previous boundary when exactly in the middle CHECK(toPhaseEncodedBeats(tl0, sec, two) == two); } TEST_CASE("toPhaseEncodedBeats | some example cases", "[Phase]") { CHECK(toPhaseEncodedBeats(tl0, microseconds{-2000000}, four) == -four); CHECK(toPhaseEncodedBeats(tl0, microseconds{-3000000}, four) == Beats{-6.}); CHECK(toPhaseEncodedBeats(tl0, microseconds{3200000}, three) == Beats{6.4}); CHECK(toPhaseEncodedBeats(tl1, microseconds{0}, three) == Beats{-11.}); CHECK(toPhaseEncodedBeats(tl1, microseconds{1500000}, Beats{2.4}) == Beats{-10.1}); } namespace { std::chrono::microseconds phaseEncodingRoundtrip( const Timeline& tl, const std::chrono::microseconds t, const Beats quantum) { return fromPhaseEncodedBeats(tl, toPhaseEncodedBeats(tl, t, quantum), quantum); } } TEST_CASE("fromPhaseEncodedBeats | inverse of toPhaseEncodedBeats", "[Phase]") { const auto t0 = microseconds{0}; const auto t1 = microseconds{2000000}; const auto t2 = microseconds{-3200000}; const auto t3 = microseconds{87654321}; CHECK(phaseEncodingRoundtrip(tl0, t0, zero) == t0); CHECK(phaseEncodingRoundtrip(tl0, t1, zero) == t1); CHECK(phaseEncodingRoundtrip(tl0, t2, zero) == t2); CHECK(phaseEncodingRoundtrip(tl0, t3, zero) == t3); CHECK(phaseEncodingRoundtrip(tl0, t0, one) == t0); CHECK(phaseEncodingRoundtrip(tl0, t1, one) == t1); CHECK(phaseEncodingRoundtrip(tl0, t2, one) == t2); CHECK(phaseEncodingRoundtrip(tl0, t3, one) == t3); CHECK(phaseEncodingRoundtrip(tl0, t0, two) == t0); CHECK(phaseEncodingRoundtrip(tl0, t1, two) == t1); CHECK(phaseEncodingRoundtrip(tl0, t2, two) == t2); CHECK(phaseEncodingRoundtrip(tl0, t3, two) == t3); CHECK(phaseEncodingRoundtrip(tl0, t0, three) == t0); CHECK(phaseEncodingRoundtrip(tl0, t1, three) == t1); CHECK(phaseEncodingRoundtrip(tl0, t2, three) == t2); CHECK(phaseEncodingRoundtrip(tl0, t3, three) == t3); CHECK(phaseEncodingRoundtrip(tl1, t0, zero) == t0); CHECK(phaseEncodingRoundtrip(tl1, t1, zero) == t1); CHECK(phaseEncodingRoundtrip(tl1, t2, zero) == t2); CHECK(phaseEncodingRoundtrip(tl1, t3, zero) == t3); CHECK(phaseEncodingRoundtrip(tl1, t0, one) == t0); CHECK(phaseEncodingRoundtrip(tl1, t1, one) == t1); CHECK(phaseEncodingRoundtrip(tl1, t2, one) == t2); CHECK(phaseEncodingRoundtrip(tl1, t3, one) == t3); CHECK(phaseEncodingRoundtrip(tl1, t0, two) == t0); CHECK(phaseEncodingRoundtrip(tl1, t1, two) == t1); CHECK(phaseEncodingRoundtrip(tl1, t2, two) == t2); CHECK(phaseEncodingRoundtrip(tl1, t3, two) == t3); CHECK(phaseEncodingRoundtrip(tl1, t0, three) == t0); CHECK(phaseEncodingRoundtrip(tl1, t1, three) == t1); CHECK(phaseEncodingRoundtrip(tl1, t2, three) == t2); CHECK(phaseEncodingRoundtrip(tl1, t3, three) == t3); } } // namespace link } // namespace ableton link-Link-1.0.0/src/ableton/test/0000755000175000017500000000000012765602651016776 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/ableton/test/catch/0000755000175000017500000000000012765602651020060 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/ableton/test/catch/CatchMain.cpp0000644000175000017500000000432212765602651022414 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #define CATCH_CONFIG_RUNNER #include #include #if LINK_PLATFORM_WINDOWS && LINK_BUILD_VLD #include #endif namespace { const char* pathForXmlOutput(const int argc, const char* const argv[]) { const std::string outputArgPrefix = "--gtest_output=xml:"; for (int i = 1; i < argc; i++) { if (outputArgPrefix.compare({argv[i], outputArgPrefix.length()}) == 0) { return argv[i] + outputArgPrefix.length(); } } return nullptr; } } // anonymous namespace int main(const int argc, const char* const argv[]) { // If google test-style output is requested, re-interpreted the argument call const auto pPath = pathForXmlOutput(argc, argv); const auto args = pPath == nullptr ? std::vector{} : std::vector{"-r", "junit", "-o", pPath}; // Filter out GTest Arguments and remove them from the input arguments std::vector inArgs(argv, argv + argc); inArgs.erase(std::remove_if(inArgs.begin(), inArgs.end(), [](const char* arg) { return std::string{arg}.find("--gtest") != std::string::npos; }), inArgs.end()); inArgs.insert(inArgs.end(), args.begin(), args.end()); Catch::Session session; session.applyCommandLine(int(inArgs.size()), inArgs.data()); return session.run(); } link-Link-1.0.0/src/ableton/test/serial_io/0000755000175000017500000000000012765602651020744 5ustar zmoelnigzmoelniglink-Link-1.0.0/src/ableton/test/serial_io/SchedulerTree.cpp0000644000175000017500000000563312765602651024215 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include #include namespace ableton { namespace test { namespace serial_io { void SchedulerTree::run() { while (handlePending()) { } } std::shared_ptr SchedulerTree::makeChild() { auto newChild = std::make_shared(); mChildren.push_back(newChild); return newChild; } void SchedulerTree::cancelTimer(const TimerId timerId) { const auto it = std::find_if( begin(mTimers), end(mTimers), [timerId](const TimerMap::value_type& timer) { return timer.first.second == timerId; }); if (it != end(mTimers)) { auto handler = std::move(it->second); mPendingHandlers.push_back([handler]() { handler(1); // truthy indicates error }); mTimers.erase(it); } } SchedulerTree::TimePoint SchedulerTree::nextTimerExpiration() { auto nextTimePoint = TimePoint::max(); withChildren([&nextTimePoint](SchedulerTree& child) { nextTimePoint = (std::min)(nextTimePoint, child.nextOwnTimerExpiration()); }); return (std::min)(nextTimePoint, nextOwnTimerExpiration()); } void SchedulerTree::triggerTimersUntil(const TimePoint t) { using namespace std; withChildren([t](SchedulerTree& child) { child.triggerTimersUntil(t); }); const auto it = mTimers.upper_bound(make_pair(t, numeric_limits::max())); for_each(begin(mTimers), it, [this](const TimerMap::value_type& timer) { mPendingHandlers.push_back([timer]() { timer.second(0); // 0 indicates no error }); }); mTimers.erase(begin(mTimers), it); } bool SchedulerTree::handlePending() { bool subtreeWorked = false; withChildren( [&subtreeWorked](SchedulerTree& child) { subtreeWorked |= child.handlePending(); }); if (mPendingHandlers.empty()) { return subtreeWorked; } else { mPendingHandlers.front()(); mPendingHandlers.pop_front(); return true; } } SchedulerTree::TimePoint SchedulerTree::nextOwnTimerExpiration() { return mTimers.empty() ? TimePoint::max() : begin(mTimers)->first.first; } } // namespace serial_io } // namespace test } // namespace ableton link-Link-1.0.0/README.md0000644000175000017500000001735312765602651015074 0ustar zmoelnigzmoelnig# Ableton Link This is the codebase for Ableton Link, a technology that synchronizes musical beat, tempo, and phase across multiple applications running on one or more devices. Applications on devices connected to a local network discover each other automatically and form a musical session in which each participant can perform independently: anyone can start or stop while still staying in time. Anyone can change the tempo, the others will follow. Anyone can join or leave without disrupting the session. # License Ableton Link is dual [licensed][license] under GNU GPL version 2 and a proprietary license. If you would like to incorporate Link into a proprietary software application, please contact . # Building and Running Link Examples Link relies on `asio-standalone` and `catch` as submodules. After checking out the main repositories, those submodules have to be loaded using ``` git submodule update --init --recursive ``` Link uses [CMake][cmake] to generate build files for the [Catch][catch]-based unit-tests and the example applications. ``` $ mkdir build $ cd build $ cmake .. $ cmake --build . ``` In order to build the GUI example application **QLinkHut**, the [Qt][qt] installation path must be set in the system PATH and `LINK_BUILD_QT_EXAMPLES` must be set: ``` $ mkdir build $ cd build $ cmake -DLINK_BUILD_QT_EXAMPLES=ON .. $ cmake --build . ``` The output binaries for the example applications and the unit-tests will be placed in a `bin` subdirectory of the CMake binary directory. Also note that the word size of the Qt installation must match how Link has been configured. Look for the value of `LINK_WORD_SIZE` in the CMake output to verify that the word size matches Qt's. When running QLinkHut on Windows, the Qt binary path must be in the system `PATH` before launching the executable. So to launch QLinkHut from Visual Studio, one must go to the QLinkHut Properties -> Debugging -> Environment, and set it to: ``` PATH=$(Path);C:\path\to\Qt\5.5\msvc64_bin\bin ``` # Integrating Link in your Application ## Test Plan To make sure users have the best possible experience using Link it is important all apps supporting Link behave consistently. This includes for example playing in sync with other apps as well as not hijacking a jams tempo when joining. To make sure your app behaves as intended make sure it complies to the [Test Plan](TEST-PLAN.md). ## Building Link Link is a header-only library, so it should be straightforward to integrate into your application. ### CMake-based Projects If you are using CMake, then you can simply add the following to your CMakeLists.txt file: ```cmake include($PATH_TO_LINK/AbletonLinkConfig.cmake) target_link_libraries($YOUR_TARGET Ableton::Link) ``` You can optionally have your build target depend on `${link_HEADERS}`, which will make the Link headers visible in your IDE. This variable exported to the `PARENT_SCOPE` by Link's CMakeLists.txt. ### Other Build Systems If you are not using CMake, then you must do the following: - Add the `link/include` directory to your list of include paths - Define `LINK_PLATFORM_MACOSX=1`, `LINK_PLATFORM_LINUX=1`, or `LINK_PLATFORM_WINDOWS=1`, depending on which platform you are building on. If you get any compiler errors/warnings, have a look at [compile-flags.cmake](cmake_include/ConfigireCompileFlags.cmake), which might provide some insight as to the compiler flags needed to build Link. ### Build Requirements | Platform | Minimum Required | Optional | |----------|------------------|------------------------| | **All** | CMake 3.0 | Qt 5.5 | | Windows | MSVC 2013 | | | Mac | Xcode 7.0 | | | Linux | Clang 3.6 | libportaudio19-dev | | Linux | GCC 5.2 | | Other compilers with good C++11 support should work, but are not verified. iOS developers should not use this repo. See http://ableton.github.io/linkkit for information on the LinkKit SDK for iOS. # Documentation An overview of Link concepts can be found at http://ableton.github.io/link. Those that are new to Link should start there. The [Link.hpp](include/ableton/Link.hpp) header contains the full Link public interface. See the LinkHut and QLinkHut projects in this repo for an example usage of the `Link` type. ## Time and Clocks Link works by calculating a relationship between the system clocks of devices in a session. Since the mechanism for obtaining a system time value and the unit of these values differ across platforms, Link defines a `Clock` abstraction with platform-specific implementations. Please see: - `Link::clock()` method in [Link.hpp](include/ableton/Link.hpp) - OSX and iOS clock implementation in [platforms/darwin/Clock.hpp](include/ableton/platforms/darwin/Clock.hpp) - Windows clock implementation in [platforms/windows/Clock.hpp](include/ableton/platforms/windows/Clock.hpp) - C++ standard library `std::chrono::high_resolution_clock`-based implementation in [platforms/stl/Clock.hpp](include/ableton/platforms/stl/Clock.hpp) Using the system time correctly in the context of an audio callback gets a little complicated. Audio devices generally have a sample clock that is independent of the system Clock. Link maintains a mapping between system time and beat time and therefore can't use the sample time provided by the audio system directly. On OSX and iOS, the CoreAudio render callback is passed an `AudioTimeStamp` structure with a `mHostTime` member that represents the system time at which the audio buffer will be passed to the audio hardware. This is precisely the information needed to derive the beat time values corresponding to samples in the buffer using Link. Unfortunately, not all platforms provide this data to the audio callback. When a system timestamp is not provided with the audio buffer, the best a client can do in the audio callback is to get the current system time and filter it based on the provided sample time. Filtering is necessary because the audio callback will not be invoked at a perfectly regular interval and therefore the queried system time will exhibit jitter relative to the sample clock. The Link library provides a [HostTimeFilter](include/ableton/link/HostTimeFilter.hpp) utility class that performs a linear regression between system time and sample time in order to improve the accuracy of system time values used in an audio callback. See the audio callback implementations for the various [platforms](examples/linkaudio) used in the examples to see how this is used in practice. Note that for Windows-based systems, we recommend using the [ASIO][asio] audio driver. ## Latency Compensation As discussed in the previous section, the system time that a client is provided in an audio callback either represents the time at which the buffer will be submitted to the audio hardware (for OSX/iOS) or the time at which the callback was invoked (when the code in the callback queries the system time). Note that neither of these is what we actually want to synchronize between devices in order to play in time. In order for multiple devices to play in time, we need to synchronize the moment at which their signals hit the speaker or output cable. If this compensation is not performed, the output signals from devices with different output latencies will exhibit a persistent offset from each other. For this reason, the audio system's output latency should be added to system time values before passing them to Link methods. Examples of this latency compensation can be found in the [platform](examples/linkaudio) implementations of the example apps. [asio]: https://www.steinberg.net/en/company/developers.html [catch]: https://github.com/philsquared/Catch [cmake]: https://www.cmake.org [license]: LICENSE.md [qt]: https://www.qt.io link-Link-1.0.0/.appveyor.yml0000644000175000017500000000325712765602651016261 0ustar zmoelnigzmoelnigclone_depth: 50 branches: only: - master # Also includes VS2013 pre-installed image: Visual Studio 2015 environment: matrix: # Visual Studio 2013, 32-bit Release, Asio driver - WORDSIZE: 32 AUDIO_DRIVER: Asio CONFIGURATION: Release GENERATOR: Visual Studio 12 2013 # Visual Studio 2013, 64-bit Release, Asio driver - WORDSIZE: 64 AUDIO_DRIVER: Asio CONFIGURATION: Release GENERATOR: Visual Studio 12 2013 Win64 # Visual Studio 2015, 32-bit Release, Asio driver - WORDSIZE: 32 AUDIO_DRIVER: Asio CONFIGURATION: Release GENERATOR: Visual Studio 14 2015 # Visual Studio 2015, 64-bit Debug, Asio driver - WORDSIZE: 64 AUDIO_DRIVER: Asio CONFIGURATION: Debug GENERATOR: Visual Studio 14 2015 Win64 # Visual Studio 2015, 64-bit Release, Asio driver - WORDSIZE: 64 AUDIO_DRIVER: Asio CONFIGURATION: Release GENERATOR: Visual Studio 14 2015 Win64 # Visual Studio 2015, 64-bit Release, Wasapi driver - WORDSIZE: 64 AUDIO_DRIVER: Wasapi CONFIGURATION: Release GENERATOR: Visual Studio 14 2015 Win64 install: - git submodule update --init --recursive - if %WORDSIZE% == 32 (set QT=msvc2013) - if %WORDSIZE% == 64 (set QT=msvc2013_64) - set PATH=%PATH%;C:\Qt\5.5\%QT%\bin build_script: - if %WORDSIZE% == 64 ( python ci/configure.py -w %WORDSIZE% -q -a %AUDIO_DRIVER% -g "%GENERATOR%" ) - if %WORDSIZE% == 32 ( python ci/configure.py -w %WORDSIZE% -q -g "%GENERATOR%" ) - python ci/build.py --configuration %CONFIGURATION% test_script: - python ci/run-tests.py --target LinkCoreTest - python ci/run-tests.py --target LinkDiscoveryTest link-Link-1.0.0/modules/0000755000175000017500000000000012765602651015254 5ustar zmoelnigzmoelniglink-Link-1.0.0/modules/asio-standalone/0000755000175000017500000000000012765602651020335 5ustar zmoelnigzmoelniglink-Link-1.0.0/modules/catch/0000755000175000017500000000000012765602651016336 5ustar zmoelnigzmoelniglink-Link-1.0.0/examples/0000755000175000017500000000000012765602651015422 5ustar zmoelnigzmoelniglink-Link-1.0.0/examples/CMakeLists.txt0000644000175000017500000001514712765602651020172 0ustar zmoelnigzmoelnigcmake_minimum_required(VERSION 3.0) project(LinkExamples) # _ ____ ___ ___ # / \ / ___|_ _/ _ \ # / _ \ \___ \| | | | | # / ___ \ ___) | | |_| | # /_/ \_\____/___\___/ # if(WIN32) function(configure_asio asio_sdk_path_OUT) # ASIO-related path/file variables set(asio_download_root "https://www.steinberg.net/sdk_downloads") set(asio_file_name "asiosdk2.3.zip") set(asio_dir_name "ASIOSDK2.3") set(asio_working_dir "${CMAKE_BINARY_DIR}/modules") set(asio_output_path "${asio_working_dir}/${asio_file_name}") message(STATUS "Downloading ASIO SDK") file(DOWNLOAD "${asio_download_root}/${asio_file_name}" ${asio_output_path}) file(SHA1 ${asio_output_path} asio_zip_hash) message(" ASIO SDK SHA1: ${asio_zip_hash}") message(" Extracting ASIO SDK") execute_process(COMMAND ${CMAKE_COMMAND} -E tar "xf" ${asio_output_path} --format=zip WORKING_DIRECTORY ${asio_working_dir} INPUT_FILE ${asio_output_path} ) # Set the ASIO SDK path for the caller set(${asio_sdk_path_OUT} "${asio_working_dir}/${asio_dir_name}" PARENT_SCOPE) endfunction() endif() # _ _ _ # / \ _ _ __| (_) ___ # / _ \| | | |/ _` | |/ _ \ # / ___ \ |_| | (_| | | (_) | # /_/ \_\__,_|\__,_|_|\___/ # set(linkhut_audio_SOURCES) if(APPLE) set(linkhut_audio_SOURCES linkaudio/AudioPlatform_CoreAudio.hpp linkaudio/AudioPlatform_CoreAudio.cpp ) elseif(WIN32) if(LINK_BUILD_ASIO) configure_asio(asio_sdk_path) include_directories(${asio_sdk_path}/common) include_directories(${asio_sdk_path}/host) include_directories(${asio_sdk_path}/host/pc) set(linkhut_audio_SOURCES ${asio_sdk_path}/common/asio.cpp ${asio_sdk_path}/host/asiodrivers.cpp ${asio_sdk_path}/host/pc/asiolist.cpp linkaudio/AudioPlatform_Asio.hpp linkaudio/AudioPlatform_Asio.cpp ) else() message(WARNING "LinkHut has been configured to be built with the WASAPI audio " "driver. This driver is considered experimental and has problems with low-latency " "playback. Please consider using the ASIO driver instead.") set(linkhut_audio_SOURCES linkaudio/AudioPlatform_Wasapi.hpp linkaudio/AudioPlatform_Wasapi.cpp ) endif() elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") set(linkhut_audio_SOURCES linkaudio/AudioPlatform_Portaudio.hpp linkaudio/AudioPlatform_Portaudio.cpp ) endif() include_directories(linkaudio) source_group("Audio Sources" FILES ${linkhut_audio_SOURCES}) # ____ # / ___|___ _ __ ___ _ __ ___ ___ _ __ # | | / _ \| '_ ` _ \| '_ ` _ \ / _ \| '_ \ # | |__| (_) | | | | | | | | | | | (_) | | | | # \____\___/|_| |_| |_|_| |_| |_|\___/|_| |_| # function(configure_linkhut_executable target) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") target_link_libraries(${target} pthread) endif() target_link_libraries(${target} Ableton::Link) target_set_word_size(${target}) endfunction() function(configure_linkhut_audio_sources target) if(APPLE) target_link_libraries(${target} "-framework AudioUnit") target_compile_definitions(${target} PRIVATE -DLINKHUT_AUDIO_PLATFORM_COREAUDIO=1 ) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") target_link_libraries(${target} asound portaudio) target_compile_definitions(${target} PRIVATE -DLINKHUT_AUDIO_PLATFORM_PORTAUDIO=1 ) elseif(WIN32) if(LINK_BUILD_ASIO) # ASIO uses lots of old-school string APIs from the C stdlib add_definitions("/D_CRT_SECURE_NO_WARNINGS") target_compile_definitions(${target} PRIVATE -DLINKHUT_AUDIO_PLATFORM_ASIO=1 ) else() target_compile_definitions(${target} PRIVATE -DLINKHUT_AUDIO_PLATFORM_WASAPI=1 ) endif() target_link_libraries(${target} winmm) endif() endfunction() if(WIN32) # When building LinkHut, additional warnings are generated from third-party frameworks set(extra_ignored_warnings_LIST "/wd4127" # conditional expression is constant "/wd4702" # unreachable code ) if(LINK_BUILD_ASIO) set(extra_ignored_warnings_LIST ${extra_ignored_warnings_LIST} "/wd4267" # 'argument': conversion from '?' to '?', possible loss of data "/wd4477" # 'printf': format string '%?' requires an argument of type '?' ) endif() string(REPLACE ";" " " extra_ignored_warnings "${extra_ignored_warnings_LIST}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${extra_ignored_warnings}") endif() # _ _ _ _ _ _ # | | (_)_ __ | | _| | | |_ _| |_ # | | | | '_ \| |/ / |_| | | | | __| # | |___| | | | | <| _ | |_| | |_ # |_____|_|_| |_|_|\_\_| |_|\__,_|\__| # set(linkhut_HEADERS linkaudio/AudioEngine.hpp linkaudio/AudioPlatform.hpp ${link_HEADERS} ) set(linkhut_SOURCES linkaudio/AudioEngine.cpp linkhut/main.cpp ) add_executable(LinkHut ${linkhut_HEADERS} ${linkhut_SOURCES} ${linkhut_audio_SOURCES} ) configure_linkhut_audio_sources(LinkHut) configure_linkhut_executable(LinkHut) source_group("LinkHut" FILES ${linkhut_HEADERS} ${linkhut_SOURCES}) # ___ _ _ _ _ _ _ # / _ \| | (_)_ __ | | _| | | |_ _| |_ # | | | | | | | '_ \| |/ / |_| | | | | __| # | |_| | |___| | | | | <| _ | |_| | |_ # \__\_\_____|_|_| |_|_|\_\_| |_|\__,_|\__| # if(LINK_BUILD_QT_EXAMPLES) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) find_package(Qt5Quick REQUIRED) set(qlinkhut_HEADERS linkaudio/AudioEngine.hpp linkaudio/AudioPlatform.hpp qlinkhut/Controller.hpp ${link_HEADERS} ) set(qlinkhut_SOURCES linkaudio/AudioEngine.cpp qlinkhut/Controller.cpp qlinkhut/main.cpp ${link_SOURCES} ) source_group("QLinkHut" FILES ${qlinkhut_HEADERS} ${qlinkhut_SOURCES}) qt5_add_resources(UI_RESOURCES qlinkhut/resources.qrc) add_executable(QLinkHut ${qlinkhut_HEADERS} ${qlinkhut_SOURCES} ${linkhut_audio_SOURCES} ${UI_RESOURCES} ) target_link_libraries(QLinkHut Qt5::Quick) configure_linkhut_audio_sources(QLinkHut) configure_linkhut_executable(QLinkHut) # A silent version of QLinkHut that uses the Link application context instead of # the audio buffer context. It is the same as QLinkHut except that it doesn't # generate sound. add_executable(QLinkHutSilent ${qlinkhut_HEADERS} ${qlinkhut_SOURCES} linkaudio/AudioPlatform_Dummy.hpp ${UI_RESOURCES} ) target_link_libraries(QLinkHutSilent Qt5::Quick) target_compile_definitions(QLinkHutSilent PRIVATE -DLINKHUT_AUDIO_PLATFORM_DUMMY=1 ) if(UNIX) set_target_properties(QLinkHutSilent PROPERTIES COMPILE_FLAGS "-Wno-unused" ) endif() configure_linkhut_executable(QLinkHutSilent) endif() link-Link-1.0.0/examples/qlinkhut/0000755000175000017500000000000012765602651017261 5ustar zmoelnigzmoelniglink-Link-1.0.0/examples/qlinkhut/BeatTile.qml0000644000175000017500000000227412765602651021472 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ import QtQuick 2.0 Rectangle { property var index: 0 property var currentBeat: -1 property var countIn: false property var activeColor: "#404040" property var countInColor: "#909090" height: 328; border.width: 1; border.color: "#FFFFFF"; color: index == currentBeat ? (countIn ? countInColor : activeColor) : "#404040" } link-Link-1.0.0/examples/qlinkhut/resources.qrc0000644000175000017500000000017112765602651022001 0ustar zmoelnigzmoelnig BeatTile.qml main.qml link-Link-1.0.0/examples/qlinkhut/Controller.cpp0000644000175000017500000000430512765602651022112 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "Controller.hpp" namespace ableton { namespace qlinkhut { Controller::Controller() : mTempo(120) , mLink(mTempo) , mAudioPlatform(mLink) { mLink.setNumPeersCallback([this](std::size_t) { Q_EMIT onNumberOfPeersChanged(); }); mLink.setTempoCallback([this](const double bpm) { mTempo = bpm; Q_EMIT onTempoChanged(); }); } void Controller::setIsPlaying(bool isPlaying) { if (isPlaying) { mAudioPlatform.mEngine.startPlaying(); } else { mAudioPlatform.mEngine.stopPlaying(); } Q_EMIT onIsPlayingChanged(); } bool Controller::isPlaying() { return mAudioPlatform.mEngine.isPlaying(); } void Controller::setTempo(double bpm) { mAudioPlatform.mEngine.setTempo(bpm); } double Controller::tempo() { return mTempo; } double Controller::quantum() { return mAudioPlatform.mEngine.quantum(); } void Controller::setQuantum(const double quantum) { mAudioPlatform.mEngine.setQuantum(quantum); Q_EMIT onQuantumChanged(); } unsigned long Controller::numberOfPeers() { return static_cast(mLink.numPeers()); } void Controller::setLinkEnabled(const bool isEnabled) { mLink.enable(isEnabled); Q_EMIT onIsLinkEnabledChanged(); } bool Controller::isLinkEnabled() { return mLink.isEnabled(); } double Controller::beatTime() { return mAudioPlatform.mEngine.beatTime(); } } // namespace qlinkhut } // namespace ableton link-Link-1.0.0/examples/qlinkhut/main.cpp0000644000175000017500000000241312765602651020711 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "Controller.hpp" #include #include #include #include #include int main(int argc, char* argv[]) { ableton::qlinkhut::Controller controller; QGuiApplication app(argc, argv); QQuickView view; view.rootContext()->setContextProperty("controller", &controller); view.setSource(QUrl("qrc:/main.qml")); view.show(); return app.exec(); } link-Link-1.0.0/examples/qlinkhut/main.qml0000644000175000017500000002035612765602651020726 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ import QtQuick 2.3 import QtQuick.Controls 1.2 import QtQuick.Layouts 1.1 Item { width: 768 height: 576 Rectangle { id: linkView x: 31 y: 25 width: 170 height: 50 border.color: "#404040" border.width: 1 color: controller.isLinkEnabled ? "#E6E6E6" : "#FFFFFF" Label { id: linkLabel property var linkEnabledText: "0 Links" text: controller.isLinkEnabled ? linkEnabledText : "Link" color: "#404040" font.pixelSize: 36 font.family: "Calibri" anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter Connections { target: controller onNumberOfPeersChanged: { linkLabel.linkEnabledText = controller.numberOfPeers + " Link" linkLabel.linkEnabledText = controller.numberOfPeers == 1 ? linkLabel.linkEnabledText : linkLabel.linkEnabledText + "s" } } } MouseArea { anchors.fill: parent onPressed: { controller.isLinkEnabled = !controller.isLinkEnabled } } } Rectangle { id: loopView x: 30 y: 90 width: 708 height: 328 function onQuantumChanged() { for(var i = loopView.children.length; i > 0 ; i--) { loopView.children[i-1].destroy() } var numSegments = Math.ceil(controller.quantum) for (var i = 0; i < numSegments; i++) { var width = loopView.width / controller.quantum var x = i * width var component = Qt.createComponent("BeatTile.qml"); var tile = component.createObject(loopView, { "index": i, "x": x, "width": x + width > loopView.width ? loopView.width - x : width, }) tile.activeColor = i == 0 ? "#FF6A00" : "#FFD500" } } Connections { target: controller onQuantumChanged: { loopView.onQuantumChanged() } } Timer { interval: 8 running: true repeat: true property var last: 1 onTriggered: { var index = controller.isPlaying ? Math.floor(controller.beatTime() % controller.quantum) : controller.quantum var countIn = index < 0; var beat = countIn ? controller.quantum + index : index for(var i = 0; i < loopView.children.length ; i++) { loopView.children[i].countIn = countIn loopView.children[i].currentBeat = beat } } } Component.onCompleted: { onQuantumChanged() } } Label { x: 31 y: 460 width: 170 height: 30 text: "Quantum"; color: "#404040" font.pixelSize: 24 font.family: "Calibri" horizontalAlignment: Text.AlignHCenter } Rectangle { id: quantumView x: 31 y: 500 width: 170 height: 50 border.width : 1 border.color: "#404040" Label { id: quantumLabel text: controller.quantum.toFixed() color: "#404040" font.pixelSize: 36 font.family: "Calibri" anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter } MouseArea { anchors.fill: parent property var clickQuantum: 0 property var clickY: 0 onPressed: { clickQuantum = controller.quantum clickY = mouseY } onPositionChanged: { var quantum = clickQuantum + 0.1 * (clickY - mouseY) controller.quantum = Math.max(1, quantum.toFixed()) } onDoubleClicked: { controller.quantum = 4 } } } Label { x: (parent.width - width) / 2 - 90 y: 460 width: 170 height: 30 text: "Tempo"; color: "#404040" font.pixelSize: 24 font.family: "Calibri" horizontalAlignment: Text.AlignHCenter } Rectangle { id: tempoView x: (parent.width - width) / 2 - 90 y: 500 width: 170 height: 50 border.width : 1 border.color: "#404040" Label { id: tempoLabel text: controller.tempo.toFixed(2) color: "#404040" font.pixelSize: 36 font.family: "Calibri" anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter } MouseArea { anchors.fill: parent property var clickTempo: 0 property var clickY: 0 onPressed: { clickTempo = controller.tempo clickY = mouseY } onPositionChanged: { var tempo = clickTempo + 0.5 * (clickY - mouseY) controller.tempo = tempo } onDoubleClicked: { controller.tempo = 120 } } } Label { x: (parent.width - width) / 2 + 90 y: 460 width: 170 height: 30 text: "Beats" color: "#404040" font.pixelSize: 24 font.family: "Calibri" horizontalAlignment: Text.AlignHCenter } Rectangle { id: beatTimeIntView x: (parent.width - width) / 2 + 90 y: 500 width: 170 height: 50 border.width: 1 border.color: "#404040" Label { id: beatTimeText color: "#404040" font.pixelSize: 36 font.family: "Calibri" anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter } } Timer { id: timer interval: 10 repeat: true running: true onTriggered: { var beatTime = controller.beatTime() beatTimeText.text = beatTime.toFixed(1) } } Rectangle { id: transportView x: parent.width - width - 31 y: 500 width: 170 height: 50 border.width: 1 border.color: "#404040" color: controller.isPlaying ? "#E6E6E6" : "#FFFFFF" Label { text: controller.isPlaying ? "Pause" : "Play"; color: "#404040" font.pixelSize: 36 font.family: "Calibri" anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter } MouseArea { anchors.fill: parent onPressed: { controller.isPlaying = !controller.isPlaying } } } Item { focus: true Keys.onPressed: { if ( event.key == 32) { controller.isPlaying = !controller.isPlaying } } } } link-Link-1.0.0/examples/qlinkhut/Controller.hpp0000644000175000017500000000411112765602651022112 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include "AudioPlatform.hpp" #include namespace ableton { namespace qlinkhut { class Controller : public QObject { Q_OBJECT Q_DISABLE_COPY(Controller) public: Controller(); void setIsPlaying(bool); bool isPlaying(); Q_SIGNAL void onIsPlayingChanged(); Q_PROPERTY(bool isPlaying READ isPlaying WRITE setIsPlaying NOTIFY onIsPlayingChanged) void setTempo(double); double tempo(); Q_SIGNAL void onTempoChanged(); Q_PROPERTY(double tempo READ tempo WRITE setTempo NOTIFY onTempoChanged) void setQuantum(double quantum); double quantum(); Q_SIGNAL void onQuantumChanged(); Q_PROPERTY(double quantum READ quantum WRITE setQuantum NOTIFY onQuantumChanged) unsigned long numberOfPeers(); Q_SIGNAL void onNumberOfPeersChanged(); Q_PROPERTY(unsigned long numberOfPeers READ numberOfPeers NOTIFY onNumberOfPeersChanged) void setLinkEnabled(bool isEnabled); bool isLinkEnabled(); Q_SIGNAL void onIsLinkEnabledChanged(); Q_PROPERTY(bool isLinkEnabled WRITE setLinkEnabled READ isLinkEnabled NOTIFY onIsLinkEnabledChanged) Q_INVOKABLE double beatTime(); private: double mTempo; Link mLink; linkaudio::AudioPlatform mAudioPlatform; }; } // namespace qlinkhut } // namespace ableton link-Link-1.0.0/examples/linkaudio/0000755000175000017500000000000012765602651017401 5ustar zmoelnigzmoelniglink-Link-1.0.0/examples/linkaudio/AudioPlatform_Portaudio.cpp0000644000175000017500000000760212765602651024706 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "AudioPlatform_Portaudio.hpp" #include #include namespace ableton { namespace linkaudio { AudioPlatform::AudioPlatform(Link& link) : mEngine(link) , mSampleTime(0.) { mEngine.setSampleRate(44100.); mEngine.setBufferSize(512); initialize(); start(); } AudioPlatform::~AudioPlatform() { stop(); uninitialize(); } int AudioPlatform::audioCallback(const void* /*inputBuffer*/, void* outputBuffer, unsigned long inNumFrames, const PaStreamCallbackTimeInfo* /*timeInfo*/, PaStreamCallbackFlags /*statusFlags*/, void* userData) { using namespace std::chrono; float* buffer = static_cast(outputBuffer); AudioPlatform& platform = *static_cast(userData); AudioEngine& engine = platform.mEngine; const auto hostTime = platform.mHostTimeFilter.sampleTimeToHostTime(platform.mSampleTime); platform.mSampleTime += inNumFrames; const auto bufferBeginAtOutput = hostTime + engine.mOutputLatency; engine.audioCallback(bufferBeginAtOutput, inNumFrames); for (unsigned long i = 0; i < inNumFrames; ++i) { buffer[i * 2] = engine.mBuffer[i]; buffer[i * 2 + 1] = engine.mBuffer[i]; } return paContinue; } void AudioPlatform::initialize() { PaError result = Pa_Initialize(); if (result) { std::cerr << "Could not initialize Audio Engine. " << result << std::endl; std::terminate(); }; PaStreamParameters outputParameters; outputParameters.device = Pa_GetDefaultOutputDevice(); if (outputParameters.device == paNoDevice) { std::cerr << "Could not get Audio Device. " << std::endl; std::terminate(); } outputParameters.channelCount = 2; outputParameters.sampleFormat = paFloat32; outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; mEngine.mOutputLatency = std::chrono::microseconds(llround(outputParameters.suggestedLatency * 1.0e6)); result = Pa_OpenStream(&pStream, NULL, &outputParameters, mEngine.mSampleRate, mEngine.mBuffer.size(), paClipOff, &audioCallback, this); if (result) { std::cerr << "Could not open stream. " << result << std::endl; std::terminate(); } if (!pStream) { std::cerr << "No valid audio stream." << std::endl; std::terminate(); } } void AudioPlatform::uninitialize() { PaError result = Pa_CloseStream(pStream); if (result) { std::cerr << "Could not close Audio Stream. " << result << std::endl; } Pa_Terminate(); if (!pStream) { std::cerr << "No valid audio stream." << std::endl; std::terminate(); } } void AudioPlatform::start() { PaError result = Pa_StartStream(pStream); if (result) { std::cerr << "Could not start Audio Stream. " << result << std::endl; } } void AudioPlatform::stop() { if (pStream == nullptr) { return; } PaError result = Pa_StopStream(pStream); if (result) { std::cerr << "Could not stop Audio Stream. " << result << std::endl; std::terminate(); } } } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform_Wasapi.cpp0000644000175000017500000002252212765602651024162 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "AudioPlatform_Wasapi.hpp" #include #include // WARNING: This file provides an audio driver for Windows using WASAPI. This driver is // considered experimental and has problems with low-latency playback. Please consider // using the ASIO driver instead. namespace ableton { namespace linkaudio { #ifndef LINKHUT_VERBOSE_LOGGING // Show information about buffer sizes and offsets in each render callback #define LINKHUT_VERBOSE_LOGGING 0 #endif // GUID identifiers used to when looking up COM enumerators and devices static const IID kMMDeviceEnumeratorId = __uuidof(MMDeviceEnumerator); static const IID kIMMDeviceEnumeratorId = __uuidof(IMMDeviceEnumerator); static const IID kAudioClientId = __uuidof(IAudioClient); static const IID kAudioRenderClientId = __uuidof(IAudioRenderClient); // Controls how large the driver's ring buffer will be, expressed in terms of // 100-nanosecond units. This value also influences the overall driver latency. static const REFERENCE_TIME kBufferDuration = 1000000; // How long to block the runloop while waiting for an event callback. static const DWORD kWaitTimeoutInMs = 2000; void fatalError(HRESULT result, LPCTSTR context) { if (result > 0) { _com_error error(result); LPCTSTR errorMessage = error.ErrorMessage(); std::cerr << context << ": " << errorMessage << std::endl; } else { std::cerr << context << std::endl; } std::terminate(); } DWORD renderAudioRunloop(LPVOID lpParam) { AudioPlatform* platform = static_cast(lpParam); return platform->audioRunloop(); } AudioPlatform::AudioPlatform(Link& link) : mEngine(link) , mDevice(nullptr) , mAudioClient(nullptr) , mRenderClient(nullptr) , mStreamFormat(nullptr) , mEventHandle(nullptr) , mAudioThreadHandle(nullptr) , mIsRunning(false) , mSampleTime(0) { initialize(); mEngine.setBufferSize(bufferSize()); mEngine.setSampleRate(mStreamFormat->nSamplesPerSec); start(); } AudioPlatform::~AudioPlatform() { // WARNING: Here be dragons! // The WASAPI driver is not thread-safe, and crashes may occur when shutting down due // to these fields being concurrently accessed in the audio thread. Introducing a mutex // in the audio thread is not an appropriate solution to fix this race condition; a more // robust solution needs to be considered instead. if (mDevice != nullptr) { mDevice->Release(); } if (mAudioClient != nullptr) { mAudioClient->Release(); } if (mRenderClient != nullptr) { mRenderClient->Release(); } CoTaskMemFree(mStreamFormat); } UINT32 AudioPlatform::bufferSize() { UINT32 bufferSize; HRESULT result = mAudioClient->GetBufferSize(&bufferSize); if (FAILED(result)) { fatalError(result, "Could not get buffer size"); return 0; // not reached } return bufferSize; } void AudioPlatform::initialize() { HRESULT result = CoInitialize(nullptr); if (FAILED(result)) { fatalError(result, "Could not initialize COM library"); } IMMDeviceEnumerator* enumerator = nullptr; result = CoCreateInstance(kMMDeviceEnumeratorId, nullptr, CLSCTX_ALL, kIMMDeviceEnumeratorId, (void**)&enumerator); if (FAILED(result)) { fatalError(result, "Could not create device instance"); } result = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &(mDevice)); if (FAILED(result)) { fatalError(result, "Could not get default audio endpoint"); } else { enumerator->Release(); enumerator = nullptr; } result = mDevice->Activate(kAudioClientId, CLSCTX_ALL, nullptr, (void**)&(mAudioClient)); if (FAILED(result)) { fatalError(result, "Could not activate audio device"); } result = mAudioClient->GetMixFormat(&(mStreamFormat)); if (FAILED(result)) { fatalError(result, "Could not get mix format"); } if (mStreamFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { WAVEFORMATEXTENSIBLE* streamFormatEx = reinterpret_cast(mStreamFormat); if (streamFormatEx->SubFormat != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) { fatalError(0, "Sorry, only IEEE floating point streams are supported"); } } else { fatalError(0, "Sorry, only extensible wave streams are supported"); } result = mAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, kBufferDuration, 0, mStreamFormat, nullptr); if (FAILED(result)) { fatalError(result, "Could not initialize audio device"); } mEventHandle = CreateEvent(nullptr, false, false, nullptr); if (mEventHandle == nullptr) { fatalError(result, "Could not create event handle"); } result = mAudioClient->GetService(kAudioRenderClientId, (void**)&(mRenderClient)); if (FAILED(result)) { fatalError(result, "Could not get audio render service"); } mIsRunning = true; LPTHREAD_START_ROUTINE threadEntryPoint = reinterpret_cast(renderAudioRunloop); mAudioThreadHandle = CreateThread(nullptr, 0, threadEntryPoint, this, 0, nullptr); if (mAudioThreadHandle == nullptr) { fatalError(GetLastError(), "Could not create audio thread"); } } void AudioPlatform::start() { UINT32 bufSize = bufferSize(); BYTE* buffer; HRESULT result = mRenderClient->GetBuffer(bufSize, &buffer); if (FAILED(result)) { fatalError(result, "Could not get render client buffer (in start audio engine)"); } result = mRenderClient->ReleaseBuffer(bufSize, 0); if (FAILED(result)) { fatalError(result, "Could not release buffer"); } result = mAudioClient->SetEventHandle(mEventHandle); if (FAILED(result)) { fatalError(result, "Could not set event handle to audio client"); } REFERENCE_TIME latency; result = mAudioClient->GetStreamLatency(&latency); if (FAILED(result)) { fatalError(result, "Could not get stream latency"); } result = mAudioClient->Start(); if (FAILED(result)) { fatalError(result, "Could not start audio client"); } } DWORD AudioPlatform::audioRunloop() { while (mIsRunning) { DWORD wait = WaitForSingleObject(mEventHandle, kWaitTimeoutInMs); if (wait != WAIT_OBJECT_0) { mIsRunning = false; mAudioClient->Stop(); return wait; } // Get the amount of padding, which basically is the amount of data in the driver's // ring buffer that is filled with unread data. Thus, subtracting this amount from // the buffer size gives the effective buffer size, which is the amount of frames // that can be safely written to the driver. UINT32 paddingFrames; HRESULT result = mAudioClient->GetCurrentPadding(&paddingFrames); if (FAILED(result)) { fatalError(result, "Could not get number of padding frames"); } const UINT32 numSamples = bufferSize() - paddingFrames; BYTE* buffer; result = mRenderClient->GetBuffer(numSamples, &buffer); if (FAILED(result)) { fatalError(result, "Could not get render client buffer (in callback)"); } const double sampleRate = static_cast(mStreamFormat->nSamplesPerSec); using namespace std::chrono; const auto bufferDuration = duration_cast(duration{numSamples / sampleRate}); const auto hostTime = mHostTimeFilter.sampleTimeToHostTime(mSampleTime); mSampleTime += numSamples; const auto bufferBeginAtOutput = hostTime + mEngine.mOutputLatency; mEngine.audioCallback(bufferBeginAtOutput, numSamples); float* floatBuffer = reinterpret_cast(buffer); for (WORD i = 0; i < numSamples; ++i) { if (i >= mEngine.mBuffer.size()) { break; } for (WORD j = 0; j < mStreamFormat->nChannels; ++j) { floatBuffer[j + (i * mStreamFormat->nChannels)] = static_cast(mEngine.mBuffer[i]); } } // Write the buffer to the audio driver and subsequently free the buffer memory result = mRenderClient->ReleaseBuffer(numSamples, 0); if (FAILED(result)) { fatalError(result, "Error rendering data"); } } // end of runloop mIsRunning = false; return 0; } // void fillBuffer(MetronomeSynth& metronome, // const UINT32 startFrame, // const UINT32 numSamples, // const UINT32 numChannels, // BYTE* buffer) //{ // float* floatBuffer = reinterpret_cast(buffer); // UINT32 frame = startFrame; // while (frame < numSamples * numChannels) // { // const float sample = static_cast(metronome.getSample()); // for (UINT32 channel = 0; channel < numChannels; ++channel) // { // floatBuffer[frame++] = sample; // } // } //} } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform_CoreAudio.cpp0000644000175000017500000001463012765602651024611 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "AudioPlatform_CoreAudio.hpp" #include #include #include namespace ableton { namespace linkaudio { AudioPlatform::AudioPlatform(Link& link) : mEngine(link) { initialize(); start(); } AudioPlatform::~AudioPlatform() { stop(); uninitialize(); } OSStatus AudioPlatform::audioCallback(void* inRefCon, AudioUnitRenderActionFlags*, const AudioTimeStamp* inTimeStamp, UInt32, UInt32 inNumberFrames, AudioBufferList* ioData) { AudioEngine* engine = static_cast(inRefCon); const auto bufferBeginAtOutput = engine->mLink.clock().ticksToMicros(inTimeStamp->mHostTime) + engine->mOutputLatency; engine->audioCallback(bufferBeginAtOutput, inNumberFrames); for (std::size_t i = 0; i < inNumberFrames; ++i) { for (UInt32 j = 0; j < ioData->mNumberBuffers; ++j) { SInt16* bufData = static_cast(ioData->mBuffers[j].mData); bufData[i] = static_cast(32761. * engine->mBuffer[i]); } } return noErr; } void AudioPlatform::initialize() { AudioComponentDescription cd = {}; cd.componentManufacturer = kAudioUnitManufacturer_Apple; cd.componentFlags = 0; cd.componentFlagsMask = 0; cd.componentType = kAudioUnitType_Output; cd.componentSubType = kAudioUnitSubType_DefaultOutput; AudioComponent component = AudioComponentFindNext(NULL, &cd); OSStatus result = AudioComponentInstanceNew(component, &mIoUnit); if (result) { std::cerr << "Could not get Audio Unit. " << result << std::endl; std::terminate(); } UInt32 size = sizeof(mEngine.mSampleRate); result = AudioUnitGetProperty(mIoUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &mEngine.mSampleRate, &size); if (result) { std::cerr << "Could not get sample rate. " << result << std::endl; std::terminate(); } std::clog << "SAMPLE RATE: " << mEngine.mSampleRate << std::endl; AudioStreamBasicDescription asbd = {}; asbd.mFormatID = kAudioFormatLinearPCM; asbd.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsNonInterleaved; asbd.mChannelsPerFrame = 2; asbd.mBytesPerPacket = sizeof(SInt16); asbd.mFramesPerPacket = 1; asbd.mBytesPerFrame = sizeof(SInt16); asbd.mBitsPerChannel = 8 * sizeof(SInt16); asbd.mSampleRate = mEngine.mSampleRate; result = AudioUnitSetProperty(mIoUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &asbd, sizeof(asbd)); if (result) { std::cerr << "Could not set stream format. " << result << std::endl; } char deviceName[512]; size = sizeof(deviceName); result = AudioUnitGetProperty(mIoUnit, kAudioDevicePropertyDeviceName, kAudioUnitScope_Global, 0, &deviceName, &size); if (result) { std::cerr << "Could not get device name. " << result << std::endl; std::terminate(); } std::clog << "DEVICE NAME: " << deviceName << std::endl; UInt32 bufferSize = 512; size = sizeof(bufferSize); result = AudioUnitSetProperty(mIoUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &bufferSize, size); if (result) { std::cerr << "Could not set buffer size. " << result << std::endl; std::terminate(); } mEngine.setBufferSize(bufferSize); UInt32 propertyResult = 0; size = sizeof(propertyResult); result = AudioUnitGetProperty(mIoUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &propertyResult, &size); if (result) { std::cerr << "Could not get buffer size. " << result << std::endl; std::terminate(); } std::clog << "BUFFER SIZE: " << propertyResult << " samples, " << propertyResult / mEngine.mSampleRate * 1e3 << " ms." << std::endl; // the buffer, stream and safety-offset latencies are part of inTimeStamp->mHostTime // within the audio callback. UInt32 deviceLatency = 0; size = sizeof(deviceLatency); result = AudioUnitGetProperty(mIoUnit, kAudioDevicePropertyLatency, kAudioUnitScope_Output, 0, &deviceLatency, &size); if (result) { std::cerr << "Could not get output device latency. " << result << std::endl; std::terminate(); } std::clog << "OUTPUT DEVICE LATENCY: " << deviceLatency << " samples, " << deviceLatency / mEngine.mSampleRate * 1e3 << " ms." << std::endl; using namespace std::chrono; const double latency = static_cast(deviceLatency) / mEngine.mSampleRate; mEngine.mOutputLatency = duration_cast(duration{latency}); AURenderCallbackStruct ioRemoteInput; ioRemoteInput.inputProc = audioCallback; ioRemoteInput.inputProcRefCon = &mEngine; result = AudioUnitSetProperty(mIoUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &ioRemoteInput, sizeof(ioRemoteInput)); if (result) { std::cerr << "Could not set render callback. " << result << std::endl; } result = AudioUnitInitialize(mIoUnit); if (result) { std::cerr << "Could not initialize audio unit. " << result << std::endl; } } void AudioPlatform::uninitialize() { OSStatus result = AudioUnitUninitialize(mIoUnit); if (result) { std::cerr << "Could not uninitialize Audio Unit. " << result << std::endl; } } void AudioPlatform::start() { OSStatus result = AudioOutputUnitStart(mIoUnit); if (result) { std::cerr << "Could not start Audio Unit. " << result << std::endl; std::terminate(); } } void AudioPlatform::stop() { OSStatus result = AudioOutputUnitStop(mIoUnit); if (result) { std::cerr << "Could not stop Audio Unit. " << result << std::endl; } } } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform_Asio.cpp0000644000175000017500000002155112765602651023632 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "AudioPlatform_Asio.hpp" namespace ableton { namespace linkaudio { void fatalError(const ASIOError result, const std::string& function) { std::cerr << "Call to ASIO function " << function << " failed"; if (result != ASE_OK) { std::cerr << " (ASIO error code " << result << ")"; } std::cerr << std::endl; std::terminate(); } double asioSamplesToDouble(const ASIOSamples& samples) { return samples.lo + samples.hi * std::pow(2, 32); } // ASIO processing callbacks ASIOTime* bufferSwitchTimeInfo(ASIOTime* timeInfo, long index, ASIOBool) { AudioPlatform* platform = AudioPlatform::singleton(); if (platform) { platform->audioCallback(timeInfo, index); } return nullptr; } void bufferSwitch(long index, ASIOBool processNow) { ASIOTime timeInfo{}; ASIOError result = ASIOGetSamplePosition( &timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime); if (result != ASE_OK) { std::cerr << "ASIOGetSamplePosition failed with ASIO error: " << result << std::endl; } else { timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid; } bufferSwitchTimeInfo(&timeInfo, index, processNow); } AudioPlatform* AudioPlatform::_singleton = nullptr; AudioPlatform* AudioPlatform::singleton() { return _singleton; } void AudioPlatform::setSingleton(AudioPlatform* platform) { _singleton = platform; } AudioPlatform::AudioPlatform(Link& link) : mEngine(link) { initialize(); mEngine.setBufferSize(mDriverInfo.preferredSize); mEngine.setSampleRate(mDriverInfo.sampleRate); setSingleton(this); start(); } AudioPlatform::~AudioPlatform() { stop(); ASIODisposeBuffers(); ASIOExit(); if (asioDrivers != nullptr) { asioDrivers->removeCurrentDriver(); } setSingleton(nullptr); } void AudioPlatform::audioCallback(ASIOTime* timeInfo, long index) { auto hostTime = std::chrono::microseconds(0); if (timeInfo->timeInfo.flags & kSystemTimeValid) { hostTime = mHostTimeFilter.sampleTimeToHostTime( asioSamplesToDouble(timeInfo->timeInfo.samplePosition)); } const auto bufferBeginAtOutput = hostTime + mEngine.mOutputLatency; ASIOBufferInfo* bufferInfos = mDriverInfo.bufferInfos; const long numSamples = mDriverInfo.preferredSize; const long numChannels = mDriverInfo.numBuffers; const double maxAmp = std::numeric_limits::max(); mEngine.audioCallback(bufferBeginAtOutput, numSamples); for (long i = 0; i < numSamples; ++i) { for (long j = 0; j < numChannels; ++j) { int* buffer = static_cast(bufferInfos[j].buffers[index]); buffer[i] = static_cast(mEngine.mBuffer[i] * maxAmp); } } if (mDriverInfo.outputReady) { ASIOOutputReady(); } } void AudioPlatform::createAsioBuffers() { DriverInfo& driverInfo = mDriverInfo; ASIOBufferInfo* bufferInfo = driverInfo.bufferInfos; driverInfo.numBuffers = 0; // Prepare input channels. Though this is not necessarily required, the opened input // channels will not work. int numInputBuffers; if (driverInfo.inputChannels > LINK_ASIO_INPUT_CHANNELS) { numInputBuffers = LINK_ASIO_INPUT_CHANNELS; } else { numInputBuffers = driverInfo.inputChannels; } for (long i = 0; i < numInputBuffers; ++i, ++bufferInfo) { bufferInfo->isInput = ASIOTrue; bufferInfo->channelNum = i; bufferInfo->buffers[0] = bufferInfo->buffers[1] = nullptr; } // Prepare output channels int numOutputBuffers; if (driverInfo.outputChannels > LINK_ASIO_OUTPUT_CHANNELS) { numOutputBuffers = LINK_ASIO_OUTPUT_CHANNELS; } else { numOutputBuffers = driverInfo.outputChannels; } for (long i = 0; i < numOutputBuffers; i++, bufferInfo++) { bufferInfo->isInput = ASIOFalse; bufferInfo->channelNum = i; bufferInfo->buffers[0] = bufferInfo->buffers[1] = nullptr; } driverInfo.numBuffers = numInputBuffers + numOutputBuffers; ASIOError result = ASIOCreateBuffers(driverInfo.bufferInfos, driverInfo.numBuffers, driverInfo.preferredSize, &(mAsioCallbacks)); if (result != ASE_OK) { fatalError(result, "ASIOCreateBuffers"); } // Now get all buffer details, sample word length, name, word clock group and latency for (long i = 0; i < driverInfo.numBuffers; ++i) { driverInfo.channelInfos[i].channel = driverInfo.bufferInfos[i].channelNum; driverInfo.channelInfos[i].isInput = driverInfo.bufferInfos[i].isInput; result = ASIOGetChannelInfo(&driverInfo.channelInfos[i]); if (result != ASE_OK) { fatalError(result, "ASIOGetChannelInfo"); } std::clog << "ASIOGetChannelInfo successful, type: " << (driverInfo.bufferInfos[i].isInput ? "input" : "output") << ", channel: " << i << ", sample type: " << driverInfo.channelInfos[i].type << std::endl; if (driverInfo.channelInfos[i].type != ASIOSTInt32LSB) { fatalError(ASE_OK, "Unsupported sample type!"); } } long inputLatency, outputLatency; result = ASIOGetLatencies(&inputLatency, &outputLatency); if (result != ASE_OK) { fatalError(result, "ASIOGetLatencies"); } std::clog << "Driver input latency: " << inputLatency << "usec" << ", output latency: " << outputLatency << "usec" << std::endl; const double bufferSize = driverInfo.preferredSize / driverInfo.sampleRate; mEngine.mOutputLatency = std::chrono::microseconds(llround(outputLatency / driverInfo.sampleRate)); mEngine.mOutputLatency += std::chrono::microseconds(llround(1.0e6 * bufferSize)); const auto totalLatency = mEngine.mOutputLatency.count(); std::clog << "Total latency: " << totalLatency << "usec" << std::endl; } void AudioPlatform::initializeDriverInfo() { ASIOError result = ASIOGetChannels(&mDriverInfo.inputChannels, &mDriverInfo.outputChannels); if (result != ASE_OK) { fatalError(result, "ASIOGetChannels"); } std::clog << "ASIOGetChannels succeeded, inputs:" << mDriverInfo.inputChannels << ", outputs: " << mDriverInfo.outputChannels << std::endl; long minSize, maxSize, granularity; result = ASIOGetBufferSize(&minSize, &maxSize, &mDriverInfo.preferredSize, &granularity); if (result != ASE_OK) { fatalError(result, "ASIOGetBufferSize"); } std::clog << "ASIOGetBufferSize succeeded, min: " << minSize << ", max: " << maxSize << ", preferred: " << mDriverInfo.preferredSize << ", granularity: " << granularity << std::endl; result = ASIOGetSampleRate(&mDriverInfo.sampleRate); if (result != ASE_OK) { fatalError(result, "ASIOGetSampleRate"); } std::clog << "ASIOGetSampleRate succeeded, sampleRate: " << mDriverInfo.sampleRate << "Hz" << std::endl; // Check wether the driver requires the ASIOOutputReady() optimization, which can be // used by the driver to reduce output latency by one block mDriverInfo.outputReady = (ASIOOutputReady() == ASE_OK); std::clog << "ASIOOutputReady optimization is " << (mDriverInfo.outputReady ? "enabled" : "disabled") << std::endl; } void AudioPlatform::initialize() { if (!loadAsioDriver(LINK_ASIO_DRIVER_NAME)) { std::cerr << "Failed opening ASIO driver for device named '" << LINK_ASIO_DRIVER_NAME << "', is the driver installed?" << std::endl; std::terminate(); } ASIOError result = ASIOInit(&mDriverInfo.driverInfo); if (result != ASE_OK) { fatalError(result, "ASIOInit"); } std::clog << "ASIOInit succeeded, asioVersion: " << mDriverInfo.driverInfo.asioVersion << ", driverVersion: " << mDriverInfo.driverInfo.driverVersion << ", name: " << mDriverInfo.driverInfo.name << std::endl; initializeDriverInfo(); ASIOCallbacks* callbacks = &(mAsioCallbacks); callbacks->bufferSwitch = &bufferSwitch; callbacks->bufferSwitchTimeInfo = &bufferSwitchTimeInfo; createAsioBuffers(); } void AudioPlatform::start() { ASIOError result = ASIOStart(); if (result != ASE_OK) { fatalError(result, "ASIOStart"); } } void AudioPlatform::stop() { ASIOError result = ASIOStop(); if (result != ASE_OK) { fatalError(result, "ASIOStop"); } } } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioEngine.hpp0000644000175000017500000000410612765602651022302 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once // Make sure to define this before is included for Windows #define _USE_MATH_DEFINES #include #include namespace ableton { namespace linkaudio { class AudioEngine { public: AudioEngine(Link& link); void startPlaying(); void stopPlaying(); bool isPlaying() const; double beatTime() const; void setTempo(double tempo); double quantum() const; void setQuantum(double quantum); private: struct EngineData { double requestedTempo; bool resetBeatTime; bool isPlaying; double quantum; }; void setBufferSize(std::size_t size); void setSampleRate(double sampleRate); EngineData pullEngineData(); void renderMetronomeIntoBuffer(Link::Timeline timeline, double quantum, std::chrono::microseconds beginHostTime, std::size_t numSamples); void audioCallback(const std::chrono::microseconds hostTime, std::size_t numSamples); Link& mLink; double mSampleRate; std::chrono::microseconds mOutputLatency; std::vector mBuffer; EngineData mSharedEngineData; EngineData mLockfreeEngineData; std::chrono::microseconds mTimeAtLastClick; std::mutex mEngineDataGuard; friend class AudioPlatform; }; } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform_CoreAudio.hpp0000644000175000017500000000262512765602651024617 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include "AudioEngine.hpp" #include namespace ableton { namespace linkaudio { class AudioPlatform { public: AudioPlatform(Link& link); ~AudioPlatform(); AudioEngine mEngine; private: static OSStatus audioCallback(void* inRefCon, AudioUnitRenderActionFlags*, const AudioTimeStamp* inTimeStamp, UInt32, UInt32 inNumberFrames, AudioBufferList* ioData); void initialize(); void uninitialize(); void start(); void stop(); AudioUnit mIoUnit; }; } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform_Wasapi.hpp0000644000175000017500000000424512765602651024171 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include "AudioEngine.hpp" #include #include #include #include // WARNING: This file provides an audio driver for Windows using WASAPI. This driver is // considered experimental and has problems with low-latency playback. Please consider // using the ASIO driver instead. namespace ableton { namespace linkaudio { #ifndef LINKHUT_VERBOSE_LOGGING // Show information about buffer sizes and offsets in each render callback #define LINKHUT_VERBOSE_LOGGING 0 #endif // Convenience function to look up the human-readable WinAPI error code, print it out, // and then terminate the application. void fatalError(HRESULT result, LPCTSTR context); DWORD renderAudioRunloop(LPVOID); class AudioPlatform { public: AudioPlatform(Link& link); ~AudioPlatform(); DWORD audioRunloop(); AudioEngine mEngine; private: UINT32 bufferSize(); void initialize(); void start(); link::HostTimeFilter mHostTimeFilter; double mSampleTime; IMMDevice* mDevice; IAudioClient* mAudioClient; IAudioRenderClient* mRenderClient; WAVEFORMATEX* mStreamFormat; HANDLE mEventHandle; HANDLE mAudioThreadHandle; std::atomic mIsRunning; #if LINKHUT_VERBOSE_LOGGING Log log; #endif }; } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioEngine.cpp0000644000175000017500000001405412765602651022300 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "AudioEngine.hpp" // Make sure to define this before is included for Windows #define _USE_MATH_DEFINES #include namespace ableton { namespace linkaudio { AudioEngine::AudioEngine(Link& link) : mLink(link) , mSampleRate(44100.) , mOutputLatency(0) , mSharedEngineData({0., false, false, 4.}) , mLockfreeEngineData(mSharedEngineData) , mTimeAtLastClick{} { } void AudioEngine::startPlaying() { std::lock_guard lock(mEngineDataGuard); mSharedEngineData.resetBeatTime = true; mSharedEngineData.isPlaying = true; } void AudioEngine::stopPlaying() { std::lock_guard lock(mEngineDataGuard); mSharedEngineData.isPlaying = false; } bool AudioEngine::isPlaying() const { return mSharedEngineData.isPlaying; } double AudioEngine::beatTime() const { const auto timeline = mLink.captureAppTimeline(); return timeline.beatAtTime(mLink.clock().micros(), mSharedEngineData.quantum); } void AudioEngine::setTempo(double tempo) { std::lock_guard lock(mEngineDataGuard); mSharedEngineData.requestedTempo = tempo; } double AudioEngine::quantum() const { return mSharedEngineData.quantum; } void AudioEngine::setQuantum(double quantum) { std::lock_guard lock(mEngineDataGuard); mSharedEngineData.quantum = quantum; } void AudioEngine::setBufferSize(std::size_t size) { mBuffer = std::vector(size, 0.); } void AudioEngine::setSampleRate(double sampleRate) { mSampleRate = sampleRate; } AudioEngine::EngineData AudioEngine::pullEngineData() { auto engineData = EngineData{}; if (mEngineDataGuard.try_lock()) { engineData.requestedTempo = mSharedEngineData.requestedTempo; mSharedEngineData.requestedTempo = 0; engineData.resetBeatTime = mSharedEngineData.resetBeatTime; mSharedEngineData.resetBeatTime = false; mLockfreeEngineData.isPlaying = mSharedEngineData.isPlaying; mLockfreeEngineData.quantum = mSharedEngineData.quantum; mEngineDataGuard.unlock(); } engineData.isPlaying = mLockfreeEngineData.isPlaying; engineData.quantum = mLockfreeEngineData.quantum; return engineData; } void AudioEngine::renderMetronomeIntoBuffer(const Link::Timeline timeline, const double quantum, const std::chrono::microseconds beginHostTime, const std::size_t numSamples) { using namespace std::chrono; // Metronome frequencies static const double highTone = 1567.98; static const double lowTone = 1108.73; // 100ms click duration static const auto clickDuration = duration{0.1}; // The number of microseconds that elapse between samples const auto microsPerSample = 1e6 / mSampleRate; for (std::size_t i = 0; i < numSamples; ++i) { double amplitude = 0.; // Compute the host time for this sample and the last. const auto hostTime = beginHostTime + microseconds(llround(i * microsPerSample)); const auto lastSampleHostTime = hostTime - microseconds(llround(microsPerSample)); // Only make sound for positive beat magnitudes. Negative beat // magnitudes are count-in beats. if (timeline.beatAtTime(hostTime, quantum) >= 0.) { // If the phase wraps around between the last sample and the // current one with respect to a 1 beat quantum, then a click // should occur. if (timeline.phaseAtTime(hostTime, 1) < timeline.phaseAtTime(lastSampleHostTime, 1)) { mTimeAtLastClick = hostTime; } const auto secondsAfterClick = duration_cast>(hostTime - mTimeAtLastClick); // If we're within the click duration of the last beat, render // the click tone into this sample if (secondsAfterClick < clickDuration) { // If the phase of the last beat with respect to the current // quantum was zero, then it was at a quantum boundary and we // want to use the high tone. For other beats within the // quantum, use the low tone. const auto freq = floor(timeline.phaseAtTime(hostTime, quantum)) == 0 ? highTone : lowTone; // Simple cosine synth amplitude = cos(2 * M_PI * secondsAfterClick.count() * freq) * (1 - sin(5 * M_PI * secondsAfterClick.count())); } } mBuffer[i] = amplitude; } } void AudioEngine::audioCallback( const std::chrono::microseconds hostTime, const std::size_t numSamples) { const auto engineData = pullEngineData(); auto timeline = mLink.captureAudioTimeline(); // Clear the buffer std::fill(mBuffer.begin(), mBuffer.end(), 0); if (engineData.resetBeatTime) { // Reset the timeline so that beat 0 lands at the beginning of // this buffer and clear the flag. timeline.requestBeatAtTime(0, hostTime, engineData.quantum); } if (engineData.requestedTempo > 0) { // Set the newly requested tempo from the beginning of this buffer timeline.setTempo(engineData.requestedTempo, hostTime); } // Timeline modifications are complete, commit the results mLink.commitAudioTimeline(timeline); if (engineData.isPlaying) { // As long as the engine is playing, generate metronome clicks in // the buffer at the appropriate beats. renderMetronomeIntoBuffer(timeline, engineData.quantum, hostTime, numSamples); } } } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform.hpp0000644000175000017500000000235712765602651022667 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #if LINKHUT_AUDIO_PLATFORM_ASIO #include "AudioPlatform_Asio.hpp" #endif #if LINKHUT_AUDIO_PLATFORM_COREAUDIO #include "AudioPlatform_CoreAudio.hpp" #endif #if LINKHUT_AUDIO_PLATFORM_DUMMY #include "AudioPlatform_Dummy.hpp" #endif #if LINKHUT_AUDIO_PLATFORM_PORTAUDIO #include "AudioPlatform_Portaudio.hpp" #endif #if LINKHUT_AUDIO_PLATFORM_WASAPI #include "AudioPlatform_Wasapi.hpp" #endif link-Link-1.0.0/examples/linkaudio/AudioPlatform_Asio.hpp0000644000175000017500000000604212765602651023635 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include "AudioEngine.hpp" #include #include #include "asiosys.h" // Should be included before asio.h #include "asio.h" #include "asiodrivers.h" // External functions in the ASIO SDK which aren't declared in the SDK headers extern AsioDrivers* asioDrivers; bool loadAsioDriver(char* name); namespace ableton { namespace linkaudio { #ifndef LINK_ASIO_DRIVER_NAME #define LINK_ASIO_DRIVER_NAME "ASIO4ALL v2" #endif #ifndef LINK_ASIO_INPUT_CHANNELS #define LINK_ASIO_INPUT_CHANNELS 0 #endif #ifndef LINK_ASIO_OUTPUT_CHANNELS #define LINK_ASIO_OUTPUT_CHANNELS 2 #endif #ifndef LINKHUT_VERBOSE_LOGGING // Show information about buffer sizes and offsets in each render callback #define LINKHUT_VERBOSE_LOGGING 1 #endif struct DriverInfo { ASIODriverInfo driverInfo; long inputChannels; long outputChannels; long preferredSize; ASIOSampleRate sampleRate; bool outputReady; long numBuffers; ASIOBufferInfo bufferInfos[LINK_ASIO_INPUT_CHANNELS + LINK_ASIO_OUTPUT_CHANNELS]; ASIOChannelInfo channelInfos[LINK_ASIO_INPUT_CHANNELS + LINK_ASIO_OUTPUT_CHANNELS]; }; // Helper functions // Convenience function to print out an ASIO error code along with the function called void fatalError(const ASIOError result, const std::string& function); double asioSamplesToDouble(const ASIOSamples& samples); ASIOTime* bufferSwitchTimeInfo(ASIOTime* timeInfo, long index, ASIOBool); void bufferSwitch(long index, ASIOBool processNow); class AudioPlatform { public: AudioPlatform(Link& link); ~AudioPlatform(); void audioCallback(ASIOTime* timeInfo, long index); AudioEngine mEngine; // Unfortunately, the ASIO SDK does not allow passing void* user data to callback // functions, so we need to keep a singleton instance of the audio engine static AudioPlatform* singleton(); static void setSingleton(AudioPlatform* platform); private: void createAsioBuffers(); void initializeDriverInfo(); void initialize(); void start(); void stop(); DriverInfo mDriverInfo; ASIOCallbacks mAsioCallbacks; link::HostTimeFilter mHostTimeFilter; static AudioPlatform* _singleton; }; } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform_Dummy.hpp0000644000175000017500000000211512765602651024032 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include "AudioEngine.hpp" namespace ableton { namespace linkaudio { class AudioPlatform { public: AudioPlatform(Link& link) : mEngine(link) { } AudioEngine mEngine; }; } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkaudio/AudioPlatform_Portaudio.hpp0000644000175000017500000000303612765602651024710 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #pragma once #include "AudioEngine.hpp" #include #include namespace ableton { namespace linkaudio { class AudioPlatform { public: AudioPlatform(Link& link); ~AudioPlatform(); AudioEngine mEngine; private: static int audioCallback(const void* inputBuffer, void* outputBuffer, unsigned long inNumFrames, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData); void initialize(); void uninitialize(); void start(); void stop(); link::HostTimeFilter mHostTimeFilter; double mSampleTime; PaStream* pStream; }; } // namespace linkaudio } // namespace ableton link-Link-1.0.0/examples/linkhut/0000755000175000017500000000000012765602651017100 5ustar zmoelnigzmoelniglink-Link-1.0.0/examples/linkhut/main.cpp0000644000175000017500000001025212765602651020530 0ustar zmoelnigzmoelnig/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * If you would like to incorporate Link into a proprietary software application, * please contact . */ #include "AudioPlatform.hpp" #include #include #include #include #include #if LINK_PLATFORM_UNIX #include #endif struct State { std::atomic running; ableton::Link link; ableton::linkaudio::AudioPlatform audioPlatform; State() : running(true) , link(120.) , audioPlatform(link) { link.enable(true); } }; void disableBufferedInput() { #if LINK_PLATFORM_UNIX termios t; tcgetattr(STDIN_FILENO, &t); t.c_lflag &= ~ICANON; tcsetattr(STDIN_FILENO, TCSANOW, &t); #endif } void enableBufferedInput() { #if LINK_PLATFORM_UNIX termios t; tcgetattr(STDIN_FILENO, &t); t.c_lflag |= ICANON; tcsetattr(STDIN_FILENO, TCSANOW, &t); #endif } void clearLine() { std::cout << " \r" << std::flush; std::cout.fill(' '); } void printHelp() { std::cout << std::endl << " < L I N K H U T >" << std::endl << std::endl; std::cout << "usage:" << std::endl; std::cout << " start / stop: space" << std::endl; std::cout << " decrease / increase tempo: w / e" << std::endl; std::cout << " decrease / increase quantum: r / t" << std::endl; std::cout << " quit: q" << std::endl << std::endl; } void printState(const std::chrono::microseconds time, const ableton::Link::Timeline timeline, const std::size_t numPeers, const double quantum) { const auto beats = timeline.beatAtTime(time, quantum); const auto phase = timeline.phaseAtTime(time, quantum); std::cout << std::defaultfloat << "peers: " << numPeers << " | " << "quantum: " << quantum << " | " << "tempo: " << timeline.tempo() << " | " << std::fixed << "beats: " << beats << " | "; for (int i = 0; i < ceil(quantum); ++i) { if (i < phase) { std::cout << 'X'; } else { std::cout << 'O'; } } clearLine(); } void input(State& state) { char in; #if LINK_PLATFORM_WINDOWS HANDLE stdinHandle = GetStdHandle(STD_INPUT_HANDLE); DWORD numCharsRead; INPUT_RECORD inputRecord; do { ReadConsoleInput(stdinHandle, &inputRecord, 1, &numCharsRead); } while ((inputRecord.EventType != KEY_EVENT) || inputRecord.Event.KeyEvent.bKeyDown); in = inputRecord.Event.KeyEvent.uChar.AsciiChar; #elif LINK_PLATFORM_UNIX in = std::cin.get(); #endif const auto tempo = state.link.captureAppTimeline().tempo(); auto& engine = state.audioPlatform.mEngine; switch (in) { case 'q': state.running = false; clearLine(); return; case 'w': engine.setTempo(tempo - 1); break; case 'e': engine.setTempo(tempo + 1); break; case 'r': engine.setQuantum(engine.quantum() - 1); break; case 't': engine.setQuantum(std::max(1., engine.quantum() + 1)); break; case ' ': if (engine.isPlaying()) { engine.stopPlaying(); } else { engine.startPlaying(); } break; } input(state); } int main(int, char**) { State state; printHelp(); std::thread thread(input, std::ref(state)); disableBufferedInput(); while (state.running) { const auto time = state.link.clock().micros(); auto timeline = state.link.captureAppTimeline(); printState( time, timeline, state.link.numPeers(), state.audioPlatform.mEngine.quantum()); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } enableBufferedInput(); thread.join(); return 0; } link-Link-1.0.0/TEST-PLAN.md0000644000175000017500000001007612765602651015441 0ustar zmoelnigzmoelnig# Test Plan Below are a set of user interactions that are expected to work consistently across all Link-enabled apps. In order to provide the best user experience, it's important that apps behave consistently with respect to these test cases. ## Tempo Changes ### TEMPO-1: Tempo changes should be transmitted between connected apps. - Open LinkHut, press **Play**, when using QLinkHut click the **Link** button to enable Link. - Open App and **enable** Link. - Without starting to play, change tempo in App **⇒** LinkHut clicks should speed up or slow down to match the tempo specified in the App. - Start playing in the App **⇒** App and LinkHut should be in sync - Change tempo in App and in LinkHut **⇒** App and LinkHut should remain in sync ### TEMPO-2: Opening an app with Link enabled should not change the tempo of an existing Link session. - Open App and **enable** Link. - Set App tempo to 100bpm. - Terminate App. - Open LinkHut, press **Play** and **enable** Link. - Set LinkHut tempo to 130bpm. - Open App and **enable** Link. **⇒** Link should be connected (“1 Link”) and the App and LinkHut’s tempo should both be 130bpm. ### TEMPO-3: When connected, loading a new document should not change the Link session tempo. - Open LinkHut, press **Play**, when using QLinkHut click the **Link** button to enable Link. - Set LinkHut tempo to 130bpm. - Open App and **enable** Link **⇒** LinkHut’s tempo should not change. - Load new Song/Set/Session with a tempo other than 130bpm **⇒** App and LinkHut tempo should both be 130bpm. ### TEMPO-4: Tempo range handling. - Open LinkHut, press **Play**, when using QLinkHut click the **Link** button to enable Link. - Open App, start Audio, and **enable** Link. - Change tempo in LinkHut to **20bpm** **⇒** App and LinkHut should stay in sync. - Change Tempo in LinkHut to **999bpm** **⇒** App and LinkHut should stay in sync. - If App does not support the full range of tempos supported by Link, it should stay in sync by switching to a multiple of the Link session tempo. ### TEMPO-5: Enabling Link does not change app's tempo if there is no Link session to join. - Open App, start playing. - Change App tempo to something other than the default. - **Enable** Link **⇒** App's tempo should not change. - Change App tempo to a new value (not the default). - **Disable** Link **⇒** App's tempo should not change. ## Beat Time These cases verify the continuity of beat time across Link operations. ### BEATTIME-1: Enabling Link does not change app's beat time if there is no Link session to join. - Open App, start playing. - **Enable** Link **⇒** No beat time jump or audible discontinuity should occur. - **Disable** Link **⇒** No beat time jump or audible discontinuity should occur. ### BEATTIME-2: App's beat time does not change if another participant joins its session. - Open App and **enable** Link. - Start playing. - Open LinkHut, whenusing QLinkHut **enable** Link **⇒** No beat time jump or audible discontinuity should occur in the App. **Note**: When joining an existing Link session, an app should adjust to the existing session's tempo and phase, which will usually result in a beat time jump. Apps that are already in a session should never have any kind of beat time or audio discontinuity when a new participant joins the session. ## Audio Engine These cases verify the correct implementation of latency compensation within an app's audio engine. ### AUDIOENGINE-1: Correct alignment of app audio with shared session - Connect the audio out of your computer to the audio in. Alternatively use [SoundFlower](https://github.com/mattingalls/Soundflower) to be able to record the output of your app and LinkHut. - Open LinkHut, press **Play**, , when using QLinkHut click the **Link** button to enable Link. - Open App and **enable** Link. - Start playing audio (preferably a short, click-like sample) with notes on the same beats as LinkHut. - Record audio within application of choice. - Validate whether onset of the sample aligns with the pulse generated by LinkHut (tolerance: less than 3 ms). link-Link-1.0.0/cmake_include/0000755000175000017500000000000012765602651016367 5ustar zmoelnigzmoelniglink-Link-1.0.0/cmake_include/AsioStandaloneConfig.cmake0000644000175000017500000000063412765602651023426 0ustar zmoelnigzmoelnigadd_library(AsioStandalone::AsioStandalone IMPORTED INTERFACE) set_property(TARGET AsioStandalone::AsioStandalone APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_LIST_DIR}/../modules/asio-standalone/asio/include ) if (WIN32) set_property(TARGET AsioStandalone::AsioStandalone APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS _WIN32_WINNT=0x0501 _SCL_SECURE_NO_WARNINGS ) endif() link-Link-1.0.0/cmake_include/ConfigureCompileFlags.cmake0000644000175000017500000001407512765602651023607 0ustar zmoelnigzmoelnigcmake_minimum_required(VERSION 3.0) set(build_flags_COMMON_LIST) set(build_flags_DEBUG_LIST) set(build_flags_RELEASE_LIST) # _ _ _ # | | | |_ __ (_)_ __ # | | | | '_ \| \ \/ / # | |_| | | | | |> < # \___/|_| |_|_/_/\_\ # if(UNIX) # Common flags for all Unix compilers set(build_flags_DEBUG_LIST "-DDEBUG=1" ) set(build_flags_RELEASE_LIST "-DNDEBUG=1" ) # Clang-specific flags if(${CMAKE_CXX_COMPILER_ID} MATCHES Clang) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "-Werror" "-Wno-deprecated" "-Wno-global-constructors" "-Wno-over-aligned" ) # GCC-specific flags # Unfortunately, we can't use -Werror on GCC, since there is no way to suppress the # warnings generated by -fpermissive. elseif(${CMAKE_CXX_COMPILER_ID} STREQUAL GNU) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "-Werror" "-Wno-multichar" ) endif() # Set word size if(${LINK_WORD_SIZE} EQUAL 32) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "-m32" ) elseif(${LINK_WORD_SIZE} EQUAL 64) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "-m64" ) else() message(FATAL_ERROR "Invalid word size '${LINK_WORD_SIZE}', must be either 32 or 64.") endif() # ASan support if(LINK_ENABLE_ASAN) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "-fsanitize=address" "-fno-omit-frame-pointer" ) endif() # __ ___ _ # \ \ / (_)_ __ __| | _____ _____ # \ \ /\ / /| | '_ \ / _` |/ _ \ \ /\ / / __| # \ V V / | | | | | (_| | (_) \ V V /\__ \ # \_/\_/ |_|_| |_|\__,_|\___/ \_/\_/ |___/ # elseif(${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC) add_definitions("/D_SCL_SECURE_NO_WARNINGS") if(LINK_BUILD_VLD) add_definitions("/DLINK_BUILD_VLD=1") else() add_definitions("/DLINK_BUILD_VLD=0") endif() set(build_flags_DEBUG_LIST "/DDEBUG=1" ) set(build_flags_RELEASE_LIST "/DNDEBUG=1" ) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "/MP" "/Wall" "/WX" "/EHsc" ############################# # Ignored compiler warnings # ############################# "/wd4061" # Enumerator 'identifier' in switch of enum 'enumeration' is not explicitly handled by a case label "/wd4242" # 'Identifier': conversion from 'type1' to 'type2', possible loss of data "/wd4265" # 'Class' : class has virtual functions, but destructor is not virtual "/wd4350" # Behavior change: 'member1' called instead of 'member2' "/wd4355" # 'This' : used in base member initializer list "/wd4365" # 'Action': conversion from 'type_1' to 'type_2', signed/unsigned mismatch "/wd4371" # Layout of class may have changed from a previous version of the compiler due to better packing of member 'member' "/wd4503" # 'Identifier': decorated name length exceeded, name was truncated "/wd4510" # 'Class': default constructor could not be generated "/wd4512" # 'Class': assignment operator could not be generated "/wd4514" # 'Function' : unreferenced inline function has been removed "/wd4571" # Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught "/wd4610" # 'Class': can never be instantiated - user defined constructor required "/wd4619" # #pragma warning: there is no warning number 'number' "/wd4625" # 'Derived class' : copy constructor was implicitly defined as deleted because a base class copy constructor is inaccessible or deleted "/wd4626" # 'Derived class' : assignment operator was implicitly defined as deleted because a base class assignment operator is inaccessible or deleted "/wd4628" # digraphs not supported with -Ze. Character sequence 'digraph' not interpreted as alternate token for 'char' "/wd4640" # 'Instance': construction of local static object is not thread-safe "/wd4668" # 'Symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' "/wd4710" # 'Function': function not inlined "/wd4711" # Function 'function' selected for inline expansion "/wd4738" # Storing 32-bit float result in memory, possible loss of performance "/wd4820" # 'Bytes': bytes padding added after construct 'member_name' ) if(MSVC_VERSION VERSION_GREATER 1800) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "/wd4464" # Relative include path contains '..' "/wd4548" # Expression before comma has no effect; expected expression with side-effect "/wd4623" # 'Derived class': default constructor could not be generated because a base class default constructor is inaccessible "/wd4868" # Compiler may not enforce left-to-right evaluation order in braced initializer list "/wd5026" # Move constructor was implicitly defined as deleted "/wd5027" # Move assignment operator was implicitly defined as deleted "/wd5031" # #pragma warning(pop): likely mismatch, popping warning state pushed in different file ) endif() if(NOT LINK_BUILD_ASIO) set(build_flags_COMMON_LIST ${build_flags_COMMON_LIST} "/wd4917" # 'Symbol': a GUID can only be associated with a class, interface or namespace # This compiler warning is generated by Microsoft's own ocidl.h, which is # used when building the WASAPI driver. ) endif() endif() # ____ _ __ _ # / ___| ___| |_ / _| | __ _ __ _ ___ # \___ \ / _ \ __| | |_| |/ _` |/ _` / __| # ___) | __/ |_ | _| | (_| | (_| \__ \ # |____/ \___|\__| |_| |_|\__,_|\__, |___/ # |___/ # Translate lists to strings string(REPLACE ";" " " build_flags_COMMON "${build_flags_COMMON_LIST}") string(REPLACE ";" " " build_flags_DEBUG "${build_flags_DEBUG_LIST}") string(REPLACE ";" " " build_flags_RELEASE "${build_flags_RELEASE_LIST}") # Set flags for different build types set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${build_flags_COMMON}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${build_flags_DEBUG}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${build_flags_RELEASE}") link-Link-1.0.0/cmake_include/ConfigureWordSize.cmake0000644000175000017500000000177712765602651023015 0ustar zmoelnigzmoelnigcmake_minimum_required(VERSION 3.0) function(target_set_WORD_SIZE target) if(APPLE) if(${LINK_WORD_SIZE} EQUAL 32) set_target_properties(${target} PROPERTIES OSX_ARCHITECTURES "i386") elseif(${LINK_WORD_SIZE} EQUAL 64) set_target_properties(${target} PROPERTIES OSX_ARCHITECTURES "x86_64") else() message(FATAL_ERROR "Invalid word size '${LINK_WORD_SIZE}', must be either 32 or 64.") endif() elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") if(${LINK_WORD_SIZE} EQUAL 32) set_target_properties(${target} PROPERTIES COMPILE_FLAGS "-m32") set_target_properties(${target} PROPERTIES LINK_FLAGS "-m32") elseif(${LINK_WORD_SIZE} EQUAL 64) set_target_properties(${target} PROPERTIES COMPILE_FLAGS "-m64") set_target_properties(${target} PROPERTIES LINK_FLAGS "-m64") else() message(FATAL_ERROR "Invalid word size '${LINK_WORD_SIZE}', must be either 32 or 64.") endif() endif() add_definitions(-DLINK_WORD_SIZE=${LINK_WORD_SIZE}) endfunction() link-Link-1.0.0/cmake_include/CatchConfig.cmake0000644000175000017500000000026412765602651021543 0ustar zmoelnigzmoelnigadd_library(Catch::Catch IMPORTED INTERFACE) set_property(TARGET Catch::Catch APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/modules/catch/single_include ) link-Link-1.0.0/assets/0000755000175000017500000000000012765602651015106 5ustar zmoelnigzmoelniglink-Link-1.0.0/CONTRIBUTING.md0000644000175000017500000000037012765602651016035 0ustar zmoelnigzmoelnig# Contributing Unfortunately we can not accept pull requests at the moment. If you found errors or have suggestions for improvements please open an issue. When reporting errors please provide a detailed description and code examples if possible.