pax_global_header00006660000000000000000000000064136140730160014513gustar00rootroot0000000000000052 comment=71f4b2f4ee6ca352e32e695d8ab1195aaef697f9 snapcast-0.18.1/000077500000000000000000000000001361407301600134165ustar00rootroot00000000000000snapcast-0.18.1/.clang-format000066400000000000000000000007541361407301600157770ustar00rootroot00000000000000--- AccessModifierOffset: '-4' AllowShortBlocksOnASingleLine: 'false' AllowShortCaseLabelsOnASingleLine: 'false' AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: 'false' AllowShortLoopsOnASingleLine: 'false' AlwaysBreakTemplateDeclarations: 'true' BreakBeforeBraces: Allman ColumnLimit: '160' IndentCaseLabels: 'true' IndentWidth: '4' Language: Cpp MaxEmptyLinesToKeep: '3' PenaltyBreakComment: '100000' PointerAlignment: Left Standard: Cpp11 UseTab: Never ... snapcast-0.18.1/.gitignore000066400000000000000000000014471361407301600154140ustar00rootroot00000000000000# Compiled Object files *.slo *.lo *.o *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Fortran module files *.mod # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app *.*~ client/snapclient server/snapserver .vscode GPATH GRTAGS GTAGS build bin android/.idea android/Snapcast/release # debian packages debian/.debhelper debian/snapclient debian/snapserver debian/debhelper-build-stamp debian/snapclient.debhelper.log debian/snapserver.debhelper.log debian/files debian/snapclient.postinst.debhelper debian/snapclient.postrm.debhelper debian/snapclient.prerm.debhelper debian/snapclient.substvars debian/snapserver.postinst.debhelper debian/snapserver.postrm.debhelper debian/snapserver.prerm.debhelper debian/snapserver.substvars snapcast-0.18.1/.gitmodules000066400000000000000000000005471361407301600156010ustar00rootroot00000000000000[submodule "externals/flac"] path = externals/flac url = https://git.xiph.org/flac.git [submodule "externals/ogg"] path = externals/ogg url = https://git.xiph.org/ogg.git [submodule "externals/tremor"] path = externals/tremor url = https://git.xiph.org/tremor.git [submodule "externals/opus"] path = externals/opus url = https://git.xiph.org/opus.git snapcast-0.18.1/.travis.yml000066400000000000000000000124051361407301600155310ustar00rootroot00000000000000language: cpp dist: trusty sudo: required group: edge matrix: include: - os: linux compiler: gcc env: - COMPILER=g++-4.9 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - ubuntu-toolchain-r-test packages: - g++-4.9 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: gcc env: - COMPILER=g++-5 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - ubuntu-toolchain-r-test packages: - g++-5 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: gcc env: - COMPILER=g++-6 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - ubuntu-toolchain-r-test packages: - g++-6 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: gcc env: - COMPILER=g++-7 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - ubuntu-toolchain-r-test packages: - g++-7 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: gcc env: - COMPILER=g++-8 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - ubuntu-toolchain-r-test packages: - g++-8 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: gcc env: - COMPILER=g++-9 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - ubuntu-toolchain-r-test packages: - g++-9 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: clang env: - COMPILER=clang++-3.9 - CXXFLAGS=-stdlib=libc++ - CC=clang-3.9 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - llvm-toolchain-trusty-3.9 packages: - clang-3.9 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: clang env: - COMPILER=clang++-4.0 - CXXFLAGS=-stdlib=libc++ - CC=clang-4.0 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - llvm-toolchain-trusty-4.0 packages: - clang-4.0 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: clang env: - COMPILER=clang++-5.0 - CXXFLAGS=-stdlib=libc++ - CC=clang-5.0 addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - llvm-toolchain-trusty-5.0 packages: - clang-5.0 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: clang env: - COMPILER=clang++-6.0 - CXXFLAGS=-stdlib=libc++ addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - llvm-toolchain-trusty-6.0 - ubuntu-toolchain-r-test packages: - clang-6.0 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon - os: linux compiler: clang env: - COMPILER=clang++-7 - CXXFLAGS=-stdlib=libc++ addons: apt: sources: - sourceline: 'ppa:mhier/libboost-latest' - llvm-toolchain-trusty-7 - ubuntu-toolchain-r-test packages: - clang-7 boost1.70 libasound2-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libavahi-client-dev avahi-daemon # build on osx - os: osx osx_image: xcode9.4 env: - MATRIX_EVAL="brew update && brew upgrade boost && brew install flac opus libvorbis" - os: osx osx_image: xcode10.3 env: - MATRIX_EVAL="brew update && brew install flac opus libvorbis" - os: osx osx_image: xcode11 env: - MATRIX_EVAL="brew update && brew install flac opus libvorbis" before_install: - eval "${MATRIX_EVAL}" script: # make sure CXX is correctly set - if [[ "${COMPILER}" != "" ]] && [[ "${TRAVIS_COMPILER}" == "gcc" ]]; then export CXX=${COMPILER}; fi - mkdir build - cd build - cmake -DCMAKE_CXX_FLAGS="$CXXFLAGS -Werror -Wall -Wextra -pedantic -Wno-unused-parameter -Wno-unused-function -O2" .. && make && sudo make install snapcast-0.18.1/CMakeLists.txt000066400000000000000000000124711361407301600161630ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.2) project(snapcast LANGUAGES CXX VERSION 0.18.1) set(PROJECT_DESCRIPTION "Multi-room client-server audio player") set(PROJECT_URL "https://github.com/badaix/snapcast") option(BUILD_SHARED_LIBS "Build snapcast in a shared context" ON) option(BUILD_STATIC_LIBS "Build snapcast in a static context" ON) option(BUILD_TESTS "Build tests (run tests with make test)" ON) option(BUILD_SERVER "Build Snapserver" ON) option(BUILD_CLIENT "Build Snapclient" ON) option(BUILD_WITH_FLAC "Build with FLAC support" ON) option(BUILD_WITH_VORBIS "Build with VORBIS support" ON) option(BUILD_WITH_TREMOR "Build with vorbis using TREMOR" ON) option(BUILD_WITH_OPUS "Build with OPUS support" ON) option(BUILD_WITH_AVAHI "Build with AVAHI support" ON) if (NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) message(FATAL_ERROR "One or both of BUILD_SHARED_LIBS or BUILD_STATIC_LIBS must be set to ON to build") endif() if (NOT BUILD_CLIENT AND NOT BUILD_SERVER) message(FATAL_ERROR "One or both of BUILD_CLIENT or BUILD_SERVER must be set to ON to build") endif() if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(MACOSX TRUE) elseif (${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD") set (FREEBSD TRUE) if (BUILD_CLIENT) message(FATAL_ERROR "Snapclient not yet supported for FreeBSD, use \"-DBUILD_CLIENT=OFF\"") endif() elseif (${CMAKE_SYSTEM_NAME} MATCHES "Android") set (ANDROID TRUE) add_definitions("-DASIO_DISABLE_STD_FUTURE") if (BUILD_SERVER) message(FATAL_ERROR "Snapserver not yet supported for Android, use \"-DBUILD_SERVER=OFF\"") endif() endif() # Configure paths if(NOT DEFINED CMAKE_INSTALL_BINDIR) SET(CMAKE_INSTALL_BINDIR bin CACHE PATH "Output directory for binary files") endif() if(NOT DEFINED CMAKE_INSTALL_LIBDIR) SET(CMAKE_INSTALL_LIBDIR lib CACHE PATH "Output directory for libraries") endif() if(NOT DEFINED CMAKE_INSTALL_INCLUDEDIR) SET(CMAKE_INSTALL_INCLUDEDIR include CACHE PATH "Output directory for header files") endif() set(INCLUDE_DIRS "${CMAKE_SOURCE_DIR}" "${CMAKE_INSTALL_INCLUDEDIR}") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/") add_definitions(-DVERSION="${PROJECT_VERSION}") set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) # Configure compiler options set(CMAKE_CXX_STANDARD 14) # Get arch include(${CMAKE_SOURCE_DIR}/cmake/TargetArch.cmake) target_architecture(ARCH) #message(STATUS "System name: ${CMAKE_SYSTEM_NAME}") #message(STATUS "Architecture: ${ARCH}") #message(STATUS "System processor: ${CMAKE_SYSTEM_PROCESSOR}") include(CheckAtomic) INCLUDE(TestBigEndian) TEST_BIG_ENDIAN(BIGENDIAN) IF(${BIGENDIAN}) add_definitions("-DIS_BIG_ENDIAN") ENDIF(${BIGENDIAN}) # Check dependencies find_package(PkgConfig REQUIRED) find_package(Threads REQUIRED) include(CMakePushCheckState) include(CheckIncludeFileCXX) if(MACOSX) set(BONJOUR_FOUND true) if (BONJOUR_FOUND) add_definitions(-DHAS_BONJOUR) endif (BONJOUR_FOUND) add_definitions(-DFREEBSD -DHAS_DAEMON) link_directories("/usr/local/lib") list(APPEND INCLUDE_DIRS "/usr/local/include") list(APPEND CMAKE_REQUIRED_INCLUDES "${INCLUDE_DIRS}") elseif(ANDROID) # add_definitions("-DNO_CPP11_STRING") else() if (BUILD_CLIENT) pkg_search_module(ALSA REQUIRED alsa) if (ALSA_FOUND) add_definitions(-DHAS_ALSA) endif (ALSA_FOUND) endif() if(BUILD_WITH_AVAHI) pkg_search_module(AVAHI avahi-client) if (AVAHI_FOUND) add_definitions(-DHAS_AVAHI) endif (AVAHI_FOUND) endif(BUILD_WITH_AVAHI) add_definitions(-DHAS_DAEMON) if(FREEBSD) add_definitions(-DFREEBSD) link_directories("/usr/local/lib") list(APPEND INCLUDE_DIRS "/usr/local/include") list(APPEND CMAKE_REQUIRED_INCLUDES "${INCLUDE_DIRS}") endif() endif() include_directories(${INCLUDE_DIRS}) include(${CMAKE_SOURCE_DIR}/cmake/CheckCXX11StringSupport.cmake) CHECK_CXX11_STRING_SUPPORT(HAS_CXX11_STRING_SUPPORT) if(NOT HAS_CXX11_STRING_SUPPORT) add_definitions("-DNO_CPP11_STRING") endif() if(BUILD_WITH_FLAC) pkg_search_module(FLAC flac) if (FLAC_FOUND) add_definitions("-DHAS_FLAC") endif (FLAC_FOUND) endif() if(BUILD_WITH_VORBIS OR BUILD_WITH_TREMOR) pkg_search_module(OGG ogg) if (OGG_FOUND) add_definitions("-DHAS_OGG") endif (OGG_FOUND) endif() if(BUILD_WITH_VORBIS) pkg_search_module(VORBIS vorbis) if (VORBIS_FOUND) add_definitions("-DHAS_VORBIS") endif (VORBIS_FOUND) endif() if(BUILD_WITH_TREMOR) pkg_search_module(TREMOR vorbisidec) if (TREMOR_FOUND) add_definitions("-DHAS_TREMOR") endif (TREMOR_FOUND) endif() if(BUILD_WITH_VORBIS) pkg_search_module(VORBISENC vorbisenc) if (VORBISENC_FOUND) add_definitions("-DHAS_VORBIS_ENC") endif(VORBISENC_FOUND) endif() if(BUILD_WITH_OPUS) pkg_search_module(OPUS opus) if (OPUS_FOUND) add_definitions("-DHAS_OPUS") endif (OPUS_FOUND) endif() find_package(Boost 1.70 REQUIRED) add_definitions("-DBOOST_ERROR_CODE_HEADER_ONLY") add_subdirectory(common) if (BUILD_SERVER) add_subdirectory(server) endif() if (BUILD_CLIENT) add_subdirectory(client) endif() snapcast-0.18.1/LICENSE000066400000000000000000001045061361407301600144310ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} 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 3 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . snapcast-0.18.1/Makefile000066400000000000000000000011421361407301600150540ustar00rootroot00000000000000.PHONY: client server all: client server reformat: find client/ -iname *.h -o -iname *.hpp -o -iname *.cpp | xargs clang-format -i find server/ -iname *.h -o -iname *.hpp -o -iname *.cpp | xargs clang-format -i find common/ -iname *.h -o -iname *.hpp -o -iname *.cpp | xargs clang-format -i server: $(MAKE) -C server client: $(MAKE) -C client clean: $(MAKE) clean -C client $(MAKE) clean -C server rm -f *~ installclient: $(MAKE) install -C client installserver: $(MAKE) install -C server uninstallclient: $(MAKE) uninstall -C client uninstallserver: $(MAKE) uninstall -C server snapcast-0.18.1/README.md000066400000000000000000000232541361407301600147030ustar00rootroot00000000000000Snapcast ======== ![Snapcast](https://raw.githubusercontent.com/badaix/snapcast/master/doc/Snapcast_800.png) **S**y**n**chronous **a**udio **p**layer [![Build Status]( https://travis-ci.org/badaix/snapcast.svg?branch=master)](https://travis-ci.org/badaix/snapcast) [![Github Releases](https://img.shields.io/github/release/badaix/snapcast.svg)](https://github.com/badaix/snapcast/releases) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/badaix) Snapcast is a multi-room client-server audio player, where all clients are time synchronized with the server to play perfectly synced audio. It's not a standalone player, but an extension that turns your existing audio player into a Sonos-like multi-room solution. The server's audio input is a named pipe `/tmp/snapfifo`. All data that is fed into this file will be sent to the connected clients. One of the most generic ways to use Snapcast is in conjunction with the music player daemon ([MPD](http://www.musicpd.org/)) or [Mopidy](https://www.mopidy.com/), which can be configured to use a named pipe as audio output. How does it work ---------------- The Snapserver reads PCM chunks from the pipe `/tmp/snapfifo`. The chunk is encoded and tagged with the local time. Supported codecs are: * **PCM** lossless uncompressed * **FLAC** lossless compressed [default] * **Vorbis** lossy compression * **Opus** lossy low-latency compression The encoded chunk is sent via a TCP connection to the Snapclients. Each client does continuous time synchronization with the server, so that the client is always aware of the local server time. Every received chunk is first decoded and added to the client's chunk-buffer. Knowing the server's time, the chunk is played out using ALSA at the appropriate time. Time deviations are corrected by * skipping parts or whole chunks * playing silence * playing faster/slower Typically the deviation is smaller than 1ms. For more information on the binary protocol, please see the [documentation](doc/binary_protocol.md). Installation ------------ You can either build and install snapcast from source, or on Debian systems install a prebuilt .deb package ### Installation from source Please follow this [guide](doc/build.md) to build Snapcast for * [Linux](doc/build.md#linux-native) * [FreeBSD](doc/build.md#freebsd-native) * [macOS](doc/build.md#macos-native) * [Android](doc/build.md#android-cross-compile) * [OpenWrt](doc/build.md#openwrtlede-cross-compile) * [Buildroot](doc/build.md#buildroot-cross-compile) * [Raspberry Pi](doc/build.md#raspberry-pi-cross-compile) ### Install Linux packages For Debian download the package for your CPU architecture from the [latest release page](https://github.com/badaix/snapcast/releases/latest), e.g. for Raspberry Pi `snapclient_0.x.x_armhf.deb` Install the package: $ sudo dpkg -i snapclient_0.x.x_armhf.deb Install missing dependencies: $ sudo apt-get -f install On OpenWrt do: $ opkg install snapclient_0.x.x_ar71xx.ipk On Alpine Linux do: $ apk add snapcast # Or for just the client: $ apk add snapcast-client # Or for just the server: $ apk add snapcast-server On Gentoo Linux do: $ emerge --ask media-sound/snapcast On Archlinux, snapcast is available through the AUR. To install, use your favorite AUR helper, or do: $ git clone https://aur.archlinux.org/snapcast $ cd snapcast $ makepkg -si SnapOS ------ For the brave of you, there is a guide with buildfiles available to build [SnapOS](https://github.com/badaix/snapos), a small and fast-booting OS to run Snapcast, coming in two flavors: [Buildroot](https://github.com/badaix/snapos/blob/master/buildroot-external/README.md) based, or [OpenWrt](https://github.com/badaix/snapos/tree/master/openwrt) based. Please note that there are no pre-built firmware packages available. Configuration ------------- After installation, Snapserver and Snapclient are started with the command line arguments that are configured in `/etc/default/snapserver` and `/etc/default/snapclient`. Allowed options are listed in the man pages (`man snapserver`, `man snapclient`) or by invoking the snapserver or snapclient with the `-h` option. The server configuration is done in `/etc/snapserver.conf`. Different streams can by configured in the `[stream]` section with a list of `stream` options, e.g.: ``` [stream] stream = pipe:///tmp/snapfifo?name=Radio&sampleformat=48000:16:2&codec=flac stream = file:///home/user/Musik/Some%20wave%20file.wav?name=File ``` The pipe stream (`stream = pipe`) will per default create the pipe. Sometimes your audio source might insist in creating the pipe itself. So the pipe creation mode can by changed to "not create, but only read mode", using the `mode` option set to `create` or `read`: stream = pipe:///tmp/snapfifo?name=Radio&mode=read" Test ---- You can test your installation by copying random data into the server's fifo file $ sudo cat /dev/urandom > /tmp/snapfifo All connected clients should play random noise now. You might raise the client's volume with "alsamixer". It's also possible to let the server play a WAV file. Simply configure a `file` stream in `/etc/snapserver.conf`, and restart the server: ``` [stream] stream = file:///home/user/Musik/Some%20wave%20file.wav?name=test ``` When you are using a Raspberry Pi, you might have to change your audio output to the 3.5mm jack: #The last number is the audio output with 1 being the 3.5 jack, 2 being HDMI and 0 being auto. $ amixer cset numid=3 1 To setup WiFi on a Raspberry Pi, you can follow this guide: https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md Control ------- Snapcast can be controlled using a [JSON-RPC API](doc/json_rpc_api/v2_0_0.md): * Set client's volume * Mute clients * Rename clients * Assign a client to a stream * ... There is an Android client [snapdroid](https://github.com/badaix/snapdroid) available in [Releases](https://github.com/badaix/snapdroid/releases/latest) and on [Google Play](https://play.google.com/store/apps/details?id=de.badaix.snapcast) ![Snapcast for Android](https://raw.githubusercontent.com/badaix/snapcast/master/doc/snapcast_android_scaled.png) There is also an unofficial WebApp from @atoomic [atoomic/snapcast-volume-ui](https://github.com/atoomic/snapcast-volume-ui). This app lists all clients connected to a server and allows you to control individually the volume of each client. Once installed, you can use any mobile device, laptop, desktop, or browser. There is also an [unofficial FHEM module](https://forum.fhem.de/index.php/topic,62389.0.html) from @unimatrix27 which integrates a snapcast controller into the [FHEM](https://fhem.de/fhem.html) home automation system. There is a [snapcast component for Home Assistant](https://home-assistant.io/components/media_player.snapcast/) which integrates a snapcast controller in to the [Home Assistant](https://home-assistant.io/) home automation system. For a web interface in Python, see [snapcastr](https://github.com/xkonni/snapcastr), based on [python-snapcast](https://github.com/happyleavesaoc/python-snapcast). This interface controls client volume and assigns streams to groups. Another web interface running on any device is [snapcast-websockets-ui](https://github.com/derglaus/snapcast-websockets-ui), running entirely in the browser, which needs [websockify](https://github.com/novnc/websockify). No configuration needed; features almost all functions; still needs some tuning for the optics. A web interface called [HydraPlay](https://github.com/mariolukas/HydraPlay) integrates Snapcast and multiple Mopidy instances. It is JavaScript based and uses Angular 7. A Snapcast web socket proxy server is needed to connect Snapcast to HydraPlay over web sockets. Setup of audio players/server ----------------------------- Snapcast can be used with a number of different audio players and servers, and so it can be integrated into your favorite audio-player solution and make it synced-multiroom capable. The only requirement is that the player's audio can be redirected into the Snapserver's fifo `/tmp/snapfifo`. In the following configuration hints for [MPD](http://www.musicpd.org/) and [Mopidy](https://www.mopidy.com/) are given, which are base of other audio player solutions, like [Volumio](https://volumio.org/) or [RuneAudio](http://www.runeaudio.com/) (both MPD) or [Pi MusicBox](http://www.pimusicbox.com/) (Mopidy). The goal is to build the following chain: audio player software -> snapfifo -> snapserver -> network -> snapclient -> alsa This [guide](doc/player_setup.md) shows how to configure different players/audio sources to redirect their audio signal into the Snapserver's fifo: * [MPD](doc/player_setup.md#mpd) * [Mopidy](doc/player_setup.md#mopidy) * [FFmpeg](doc/player_setup.md#ffmpeg) * [mpv](doc/player_setup.md#mpv) * [MPlayer](doc/player_setup.md#mplayer) * [Alsa](doc/player_setup.md#alsa) * [PulseAudio](doc/player_setup.md#pulseaudio) * [AirPlay](doc/player_setup.md#airplay) * [Spotify](doc/player_setup.md#spotify) * [Process](doc/player_setup.md#process) * [Line-in](doc/player_setup.md#line-in) Roadmap ------- Unordered list of features that should make it into the v1.0 - [X] **Remote control** JSON-RPC API to change client latency, volume, zone,... - [X] **Android client** JSON-RPC client and Snapclient - [X] **Streams** Support multiple streams - [X] **Debian packages** prebuild deb packages - [X] **Endian** independent code - [X] **OpenWrt** port Snapclient to OpenWrt - [X] **Hi-Res audio** support (like 192kHz 24bit) - [X] **Groups** support multiple Groups of clients ("Zones") - [ ] **JSON-RPC** Possibility to add, remove, rename streams - [ ] **Protocol specification** Snapcast binary streaming protocol, JSON-RPC protocol - [ ] **Ports** Snapclient for Windows, ~~Mac OS X~~,... snapcast-0.18.1/TODO.md000066400000000000000000000011701361407301600145040ustar00rootroot00000000000000TODO ==== General ------- - Server ping client? - LastSeen: relative time [s] or [ms]? - Android crash: Empty latency => app restart => empty client list - Android clean data structures after changing the Server - UDP based audio streaming Server ------ - Provide io_context to stream-readers - [fd stream](https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer-plugins/html/gstreamer-plugins-fdsink.html) - UDP/TCP stream - gstreamer snapcast sink plugin? - "sync" option for streams (realtime reading vs read as much as available) - Override conf file settings on command line Client ------ - revise asio stuff snapcast-0.18.1/changelog.md000066400000000000000000000343551361407301600157010ustar00rootroot00000000000000# Snapcast changelog ## Version 0.18.1 ### Bugfixes - Fix random server crash or deadlock during stream client disconnect - Fix random server crash or deadlock during control client disconnect - Fix airplay stream buffer allocation (PR #536) _Johannes Pohl Tue, 28 Jan 2020 00:13:37 +0200_ ## Version 0.18.0 ### Features - Add TCP stream reader - Configurable number of server worker threads ### Bugfixes - Client: fix hostname reporting on Android - Fix some small memory leaks - Fix Librespot stream causing zombie processes (Issue #530) - Process stream watchdog is configurable (Issue #517) - Fix Makefile for macOS (Issues #510, #514) ### General - Refactored stream readers - Server can run on a single thread _Johannes Pohl Wed, 22 Jan 2020 00:13:37 +0200_ ## Version 0.17.1 ### Bugfixes - Fix compile error if u_char is not defined (Issue #506) - Fix error "exception unknown codec ogg" (Issue #504) - Fix random crash during client disconnect _Johannes Pohl Sat, 23 Nov 2019 00:13:37 +0200_ ## Version 0.17.0 ### Features - Support for Opus low-latency codec (PR #4) ### Bugfixes - CMake: fix check for libatomic (Issue #490, PR #494) - WebUI: interface.html uses the server's IP for the websocket connection - Fix warnings (Issue #484) - Fix lock order inversions and data races identified by thread sanitizer - Makefiles: fix install targets (PR #493) - Makefiles: LDFLAGS are added from environment (PR #492) - CMake: required Boost version is raised to 1.70 (Issue #488) - Fix crash in websocket server ### General - Stream server uses less threads (one in total, instead of 1+2n) - Changing group volume is much more responsive for larger groups - Unknown snapserver.conf options are logged as warning (Issue #487) - debian scripts: change usernames back to snapclient and snapserver _Johannes Pohl Wed, 20 Nov 2019 00:13:37 +0200_ ## Version 0.16.0 ### Features - Control server: websocket support for JSON RPC - Control server: simple webserver integrated to host web UIs - Control server: bind-to addresses are configurable - Control server: streams can be added and Removed (PR #443) - Control server: group names can be changed (PR #467) - Librespot: add onevent parameter (PR #465) ### Bugfixes - Fix build on macOS (Issue #474) ### General - Control server uses less threads (one in total, instead of 1+2n) - Snapserver: Configuration is moved into a file - Removed submodules "popl" and "aixlog" to ease build - Snapcast depends on boost::asio and boost::beast (header only) - Tidy up code base - Makefile doesn't statically link libgcc and libstdc++ - debian scripts: change usernames to _snapclient and _snapserver _Johannes Pohl Sat, 13 Oct 2019 00:13:37 +0200_ ## Version 0.15.0 ### Bugfixes - Snapserver: fix occasional deadlock - Snapclient: make systemd dependeny to avahi-daemon optional - cmake: fix build on FreeBSD ### General - additional linker flags "ADD_LDFLAGS" can be passed to makefile - update man pages, fix lintian warnings - Support Android NDK r17 _Johannes Pohl Sat, 07 Jul 2018 00:13:37 +0200_ ## Version 0.14.0 ### Features - Snapserver supports IPv4v6 dual stack and IPv4 + IPv6 ### Bugfixes - cmake: fix check for big endian (Issue #367) - cmake: fix linking against libatomic (PR #368) - Snapclient compiles with Android NDK API level 16 (Issue #365) - Fix compilation errors on FreeBSD (Issue #374, PR #375) ### General - cmake: make dependency on avahi optional (PR #378) - cmake: Options to build snapserver and snapclient - cmake: works on FreeBSD - Update external libs (JSON for modern C++, ASIO, AixLog) - Restructured source tree - Moved Android app into seperate project [snapdroid](https://github.com/badaix/snapdroid) _Johannes Pohl Fri, 27 Apr 2018 00:13:37 +0200_ ## Version 0.13.0 ### Features - Support "volume" parameter for Librespot (PR #273) - Add support for metatags (PR #319) ### Bugfixes - Fix overflow in timesync when the system time is many years off - Zeroconf works with IPv6 - Snapclient unit file depends on avahi-daemon.service (PR #348) ### General - Drop dependency to external "jsonrpc++" - Move OpenWrt and Buildroot support into separate project "[SnapOS](https://github.com/badaix/snapos)" - Add CMake support (not fully replacing Make yet) (PR #212) - Remove MIPS support for Android (deprecated by Google) - Use MAC address as default client id (override with "--hostID") _Johannes Pohl Tue, 04 Mar 2018 00:13:37 +0200_ ## Version 0.12.0 ### Features - Support for IPv6 (PR #273, #279) - Spotify plugin: onstart and onstop parameter (PR #225) - Snapclient: configurable client id (Issue #249) - Android: Snapclient support for ARM, MIPS and X86 - Snapserver: Play some silence before going idle (PR #284) ### Bugfixes - Fix linker error (Issue #255, #274) - Snapclient: more reliable unique client id (Issue #249, #246) - Snapserver: fix config file permissions (Issue #251) - Snapserver: fix crash on `bye` from control client (Issue #238) - Snapserver: fix crash on port scan (Issue #267) - Snapserver: fix crash when a malformed message is received (Issue #264) ### General - Improved logging: Use `--debug` for debug logging - Log to file: Use `--debug=` - Improved exception handling and error logging (Issue #276) - Android: update to NDK r16 and clang++ - hide spotify credentials in json control message (Issue #282) _Johannes Pohl Tue, 17 Oct 2017 00:13:37 +0200_ ## Version 0.11.1 ### Features - Snapserver produces high CPU load on some systems (Issue #174) - Snapserver compile error on FreeBSD ### General - Updated Markdown files (PR #216, #218) _Johannes Pohl Tue, 21 Mar 2017 00:13:37 +0200_ ## Version 0.11.0 ### Features - Don't send audio to muted clients (Issue #109, #150) - Snapclient multi-instance support (Issue #73) - daemon can run as different user (default: snapclient, Issue #89) - Spotify plugin does not require username and password (PR #181) - Spotify plugin is compatible to librespot's pipe backend (PR #158) - Clients are organized in Groups - JSON RPC API: Support batch requests ### Bugfixes - Compilation error on recent GCC versions (Issues #146, #170) - Crash when frequently connecting to the control port (Issue #200) - Snapcast App crashes on Android 4.x (Issue #207) - Resync issue on macOS (Issue #156) - Id in JSON RPC API can be String, Number or NULL (Issue #161) - Use "which" instead of "whereis" to find binaries (PR #196, Issue #185) - Compiles on lede (Issue #203) ### General - JSON RPC API is versionized (current version is 2.0.0) - Restructured Android App to support Groups _Johannes Pohl Thu, 16 Mar 2017 00:13:37 +0200_ ## Version 0.11.0-beta-1 ### Features - Snapclient multi-instance support (Issue #73) - daemon can run as different user (default: snapclient, Issue #89) - Spotify plugin does not require username and password (PR #181) - Spotify plugin is compatible to librespot's pipe backend (PR #158) - Clients are organized in Groups - JSON RPC API: Support batch requests ### Bugfixes - Resync issue on macOS (Issue #156) - Id in JSON RPC API can be String, Number or NULL (Issue #161) - Use "which" instead of "whereis" to find binaries (PR #196, Issue #185) - Compiles on lede (Issue #203) ### General - JSON RPC API is versionized (current version is 2.0.0) - Restructured Android App to support Groups _Johannes Pohl Sat, 04 Mar 2017 00:13:37 +0200_ ## Version 0.10.0 ### Features - Added support [process](https://github.com/badaix/snapcast/blob/master/doc/player_setup.md#process) streams: Snapserver starts a process and reads PCM data from stdout - Specialized versions for [Spotify](https://github.com/badaix/snapcast/blob/master/doc/player_setup.md#spotify) and [AirPlay](https://github.com/badaix/snapcast/blob/master/doc/player_setup.md#airplay) ### Bugfixes - Fixed crash during server shutdown - Fixed Makefile for FreeBSD - Fixed building of dpk (unsigned .changes file) ### General - Speed up client and server shutdown _Johannes Pohl Wed, 16 Nov 2016 00:13:37 +0200_ ## Version 0.9.0 ### Features - Added (experimental) support for macOS (make TARGET=MACOS) ### Bugfixes - Android client: Fixed crash on Nougat (Issue #97) - Fixed FreeBSD compile error for Snapserver (Issue #107) - Snapserver randomly dropped JSON control messages - Long command line options (like `--sampleformat`) didn't work on some systems (Issue #103) ### General - Updated Android NDK to revision 13 _Johannes Pohl Sat, 22 Oct 2016 00:13:37 +0200_ ## Version 0.8.0 ### Features - Added support for FreeBSD (Issue #67) - Android client: Added Japanese and German translation - Android client: Added support for ogg (Issue #83) ### Bugfixes - OpenWRT: makefile automatically sets correct endian (Issue #91) _Johannes Pohl Sun, 24 Jul 2016 00:13:37 +0200_ ## Version 0.7.0 ### Features - Support for HiRes audio (e.g. 96000:24:2) (Issue #13) - Bitdepth must be one of 8, 16, 24 (=24 bit padded to 32) or 32 - Auto start option for Android (Issue #49) - Creation mode for the fifo can be configured (Issue #52) - "-s pipe:///tmp/snapfifo?mode=[read|create]" ### Bugfixes - Server was sometimes crashing during shutdown - Exceptions were not properly logged (e.g. unsupported sample rates) - Fixed default sound card detection on OpenWrt _Johannes Pohl Sat, 07 May 2016 00:13:37 +0200_ ## Version 0.6.0 ### Features - Port to OpenWrt (Issue #18) ### Bugfixes - Android client: fixed crash if more than two streams are active (Issue #47) ### General - Support Tremor, an integer only Ogg-Vorbis implementation - Endian-independent code (Issue #18) - Cleaned up build process _Johannes Pohl Sun, 10 Apr 2016 00:02:00 +0200_ ## Version 0.5.0 ### Features - Android client: Fast switching of clients between streams ### Bugfixes - Server: Fixed reading of server.json config file ### General - Source code cleanups _Johannes Pohl Fri, 25 Mar 2016 00:02:00 +0200_ ## Version 0.4.1 ### General - Debian packages (.deb) are linked statically against libgcc and libstdc++ to improve compatibility _Johannes Pohl Sat, 12 Mar 2016 12:00:00 +0200_ ## Version 0.5.0-beta-2 ### Features - Remote control API (JSON) - Added version information - Stream playing state (unknown, idle, playing, inactive) (Issue #34) - Android client: manually configure snapserver host name - Android client compatibility improved: armeabi and armeabi-v7 binaries - Android client: configurable latency - Improved compatibility to Mopidy (GStreamer) (Issue #23) ### Bugfixes - Android client: fixed "hide offline" on start - Store config in /var/lib/snapcast/ when running as daemon (Issue #33) ### General - README.md: Added resampling command to the Mopidy section (Issue #32) _Johannes Pohl Wed, 09 Mar 2016 00:02:00 +0200_ ## Version 0.5.0-beta-1 ### Features - Remote control API (JSON) - Get server status, get streams, get active clients, ... - Assign volume, assign stream, rename client, ... - Android port of the Snapclient with a remote control app (requires API level 16, Android 4.1) - Multiple streams ("zones") can be configured using `-s, --stream` The stream is configured by an URI: path, name, codec, sample format, ... E.g. `pipe:///tmp/snapfifo?name=Radio&sampleformat=48000:16:2&codec=flac` or `file:///home/user/some_pcm_file.wav?name=file` - Added .default file for the service in `/etc/default/snapserver` and `/etc/default/snapclient`. Default program options should be configured here (e.g. streams) ### Bugfixes - Pipe reader recovers if the pipe has been reopened ### General - SnapCast is renamed to Snapcast - SnapClient => Snapclient - SnapServer => Snapserver - Changed default sample rate to 48kHz. The sample rate can be configured per stream `-s "pipe:///tmp/snapfifo?name=default&sampleformat=44100:16:2`. The default can be changed with `--sampleformat 44100:16:2` - Snapcast protocol: Less messaging: SampleFormat, Command, Ack, String, not yet final - Removed dependency to boost _Johannes Pohl Tue, 09 Feb 2016 13:25:00 +0200_ ## Version 0.4.0 ### Features - Debian packages (.deb) for amd64 and armhf - Added man pages ### Bugfixes - Snapserver and Snapclient are started as daemon on systemd systems (e.g. ARCH, Debian Jessie) ### General - Snapserver is started with normal process priority (changed nice from -3 to 0) _Johannes Pohl Mon, 28 Dec 2015 12:00:00 +0200_ ## Version 0.3.4 ### Bugfixes - Fix synchronization bug in FLAC decoder that could cause audible dropouts _Johannes Pohl Wed, 23 Dec 2015 12:00:00 +0200_ ## Version 0.3.3 ### Bugfixes - Fix Segfault when ALSA device has no description _Johannes Pohl Sun, 15 Nov 2015 12:00:00 +0200_ ## Version 0.3.2 ### General - Makefile uses CXX instead of CC to invoke the c++ compiler ### Bugfixes - Time calculation for PCM chunk play-out was wrong on some gcc versions _Johannes Pohl Wed, 30 Sep 2015 12:00:00 +0200_ ## Version 0.3.1 ### General - Improved stability over WiFi by avoiding simultaneous reads/writes on the socket connection ### Bugfixes - Fixed a bug in avahi browser _Johannes Pohl Wed, 26 Aug 2015 12:00:00 +0200_ ## Version 0.3.0 ### Features - Configurable codec options. Run `snapserver -c [flac|ogg|pcm]:?` to get supported options for the codec - Configurable buffer size for the pipe reader (default 20ms, was 50ms before) - Process priority can be changed as argument to the daemon option `-d`. Default priority is -3 ### Bugfixes - Fixed deadlock in logger - Fixed occasional timeouts for client to server requests (e.g. time sync commands) - Client didn't connect to a local server if the loopback device is the only device with an address ### General - Code clean up - Refactored encoding for lower latency _Johannes Pohl Sun, 16 Aug 2015 19:25:51 +0100 ## Version 0.2.1 ### Features - Arch Linux compatibility _Johannes Pohl Fri, 24 Jul 2015 15:47:00 +0100 snapcast-0.18.1/client/000077500000000000000000000000001361407301600146745ustar00rootroot00000000000000snapcast-0.18.1/client/CMakeLists.txt000066400000000000000000000047611361407301600174440ustar00rootroot00000000000000set(CLIENT_SOURCES client_connection.cpp controller.cpp snapclient.cpp stream.cpp time_provider.cpp decoder/pcm_decoder.cpp player/player.cpp) set(CLIENT_LIBRARIES ${CMAKE_THREAD_LIBS_INIT} common) set(CLIENT_INCLUDE ${Boost_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/client ${CMAKE_SOURCE_DIR}/common ${ASIO_INCLUDE_DIRS} ${POPL_INCLUDE_DIRS}) if(MACOSX) # Bonjour if (BONJOUR_FOUND) list(APPEND CLIENT_SOURCES browseZeroConf/browse_bonjour.cpp) endif (BONJOUR_FOUND) # CoreAudio add_definitions(-DHAS_COREAUDIO) list(APPEND CLIENT_SOURCES player/coreaudio_player.cpp) find_library(COREAUDIO_LIB CoreAudio) find_library(COREFOUNDATION_LIB CoreFoundation) find_library(AUDIOTOOLBOX_LIB AudioToolbox) list(APPEND CLIENT_LIBRARIES ${COREAUDIO_LIB} ${COREFOUNDATION_LIB} ${AUDIOTOOLBOX_LIB}) else() # Avahi if (AVAHI_FOUND) list(APPEND CLIENT_SOURCES browseZeroConf/browse_avahi.cpp) list(APPEND CLIENT_LIBRARIES ${AVAHI_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${AVAHI_INCLUDE_DIRS}) endif (AVAHI_FOUND) # ALSA if (ALSA_FOUND) list(APPEND CLIENT_SOURCES player/alsa_player.cpp) list(APPEND CLIENT_LIBRARIES ${ALSA_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${ALSA_INCLUDE_DIRS}) endif (ALSA_FOUND) endif (MACOSX) # if OGG then tremor or vorbis if (OGG_FOUND) list(APPEND CLIENT_SOURCES decoder/ogg_decoder.cpp) list(APPEND CLIENT_LIBRARIES ${OGG_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${OGG_INCLUDE_DIRS}) endif (OGG_FOUND) # Tremor (fixed-point) or libvorbis (floating-point) if (TREMOR_FOUND) list(APPEND CLIENT_LIBRARIES ${TREMOR_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${TREMOR_INCLUDE_DIRS}) elseif (VORBIS_FOUND) list(APPEND CLIENT_LIBRARIES ${VORBIS_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${VORBIS_INCLUDE_DIRS}) endif (TREMOR_FOUND) if (FLAC_FOUND) list(APPEND CLIENT_SOURCES decoder/flac_decoder.cpp) list(APPEND CLIENT_LIBRARIES ${FLAC_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${FLAC_INCLUDE_DIRS}) endif (FLAC_FOUND) if (OPUS_FOUND) list(APPEND CLIENT_SOURCES decoder/opus_decoder.cpp) list(APPEND CLIENT_LIBRARIES ${OPUS_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${OPUS_INCLUDE_DIRS}) endif (OPUS_FOUND) include_directories(${CLIENT_INCLUDE}) add_executable(snapclient ${CLIENT_SOURCES}) target_link_libraries(snapclient ${CLIENT_LIBRARIES}) install(TARGETS snapclient COMPONENT client DESTINATION "${CMAKE_INSTALL_BINDIR}") snapcast-0.18.1/client/Makefile000066400000000000000000000150431361407301600163370ustar00rootroot00000000000000# This file is part of snapcast # Copyright (C) 2014-2020 Johannes Pohl # # 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 3 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 . VERSION = 0.18.1 BIN = snapclient ifeq ($(TARGET), FREEBSD) SHELL = /usr/local/bin/bash else SHELL = /bin/bash endif ifdef DESTDIR # dh_auto_install (Debian) sets this variable TARGET_DIR = $(DESTDIR)/usr else TARGET_DIR ?= /usr endif DEBUG ?= 0 ifeq ($(DEBUG), 1) CXXFLAGS += -g else CXXFLAGS += -O2 endif ifneq ($(SANITIZE), ) CXXFLAGS += -fsanitize=$(SANITIZE) -g LDFLAGS += -fsanitize=$(SANITIZE) endif CXXFLAGS += $(ADD_CFLAGS) -std=c++14 -Wall -Wextra -Wpedantic -Wno-unused-function -DBOOST_ERROR_CODE_HEADER_ONLY -DHAS_FLAC -DHAS_OGG -DHAS_OPUS -DVERSION=\"$(VERSION)\" -I. -I.. -I../common LDFLAGS += $(ADD_LDFLAGS) -logg -lFLAC -lopus OBJ = snapclient.o stream.o client_connection.o time_provider.o player/player.o decoder/pcm_decoder.o decoder/ogg_decoder.o decoder/flac_decoder.o decoder/opus_decoder.o controller.o ../common/sample_format.o ifneq (,$(TARGET)) CXXFLAGS += -D$(TARGET) endif ifeq ($(ENDIAN), BIG) CXXFLAGS += -DIS_BIG_ENDIAN endif ifeq ($(TARGET), ANDROID) CXX = $(PROGRAM_PREFIX)clang++ CXXFLAGS += -pthread -fPIC -DHAS_TREMOR -DHAS_OPENSL -I$(NDK_DIR)/include LDFLAGS = -L$(NDK_DIR)/lib -pie -lvorbisidec -logg -lopus -lFLAC -lOpenSLES -latomic -llog -static-libstdc++ OBJ += player/opensl_player.o else ifeq ($(TARGET), OPENWRT) CXXFLAGS += -pthread -DNO_CPP11_STRING -DHAS_TREMOR -DHAS_ALSA -DHAS_AVAHI -DHAS_DAEMON LDFLAGS += -lasound -lvorbisidec -lavahi-client -lavahi-common -latomic OBJ += ../common/daemon.o player/alsa_player.o browseZeroConf/browse_avahi.o else ifeq ($(TARGET), BUILDROOT) CXXFLAGS += -pthread -DNO_CPP11_STRING -DHAS_TREMOR -DHAS_ALSA -DHAS_AVAHI -DHAS_DAEMON LDFLAGS += -lasound -lvorbisidec -lavahi-client -lavahi-common -latomic OBJ += ../common/daemon.o player/alsa_player.o browseZeroConf/browse_avahi.o else ifeq ($(TARGET), MACOS) CXX = g++ CXXFLAGS += -DHAS_COREAUDIO -DHAS_VORBIS -DFREEBSD -DHAS_BONJOUR -DHAS_DAEMON -I/usr/local/include -Wno-unused-local-typedef -Wno-deprecated LDFLAGS += -lvorbis -lFLAC -L/usr/local/lib -framework AudioToolbox -framework CoreAudio -framework CoreFoundation -framework IOKit OBJ += ../common/daemon.o player/coreaudio_player.o browseZeroConf/browse_bonjour.o else CXX = g++ CXXFLAGS += -pthread -DHAS_VORBIS -DHAS_ALSA -DHAS_AVAHI -DHAS_DAEMON LDFLAGS += -lrt -lasound -lvorbis -lavahi-client -lavahi-common -latomic OBJ += ../common/daemon.o player/alsa_player.o browseZeroConf/browse_avahi.o endif all: check-env $(BIN) check-env: ifeq ($(TARGET), ANDROID) ifndef NDK_DIR $(error android NDK_DIR is not set) endif ifndef ARCH $(error ARCH is not set (arm, mips, x86)) endif ifeq ($(ARCH), x86) $(eval PROGRAM_PREFIX:=$(NDK_DIR)/bin/i686-linux-android-) else ifeq ($(ARCH), mips) $(eval CXXFLAGS:=$(CXXFLAGS) -DIS_BIG_ENDIAN) $(eval PROGRAM_PREFIX:=$(NDK_DIR)/bin/mipsel-linux-android-) else ifeq ($(ARCH), arm) $(eval CXXFLAGS:=$(CXXFLAGS) -march=armv7) $(eval PROGRAM_PREFIX:=$(NDK_DIR)/bin/arm-linux-androideabi-) else ifeq ($(ARCH), arm64) $(eval PROGRAM_PREFIX:=$(NDK_DIR)/bin/aarch64-linux-android-) endif endif $(BIN): $(OBJ) $(CXX) $(CXXFLAGS) -o $(BIN) $(OBJ) $(LDFLAGS) %.o: %.cpp $(CXX) $(CXXFLAGS) -c $< -o $@ clean: rm -rf $(BIN) $(OBJ) *~ player/*.o ifdef DESTDIR install: $(MAKE) installfiles else ifeq ($(TARGET), MACOS) install: echo macOS install -s -g wheel -o root $(BIN) $(TARGET_DIR)/local/bin/$(BIN) install -g wheel -o root $(BIN).1 $(TARGET_DIR)/local/share/man/man1/$(BIN).1 install -g wheel -o root etc/$(BIN).plist /Library/LaunchAgents/de.badaix.snapcast.$(BIN).plist launchctl load /Library/LaunchAgents/de.badaix.snapcast.$(BIN).plist else install: $(MAKE) adduser $(MAKE) installfiles install -g audio -o snapclient -d /var/run/$(BIN) @if [[ `systemctl` =~ -\.mount ]]; then \ $(MAKE) installsystemd; \ elif [[ `/sbin/init --version` =~ upstart ]]; then \ $(MAKE) installsysv; \ elif [[ -f /etc/init.d/cron && ! -h /etc/init.d/cron ]]; then \ $(MAKE) installsysv; \ else \ echo cannot tell; \ fi; \ endif installfiles: install -s -D -g root -o root $(BIN) $(TARGET_DIR)/bin/$(BIN) install -D -g root -o root $(BIN).1 $(TARGET_DIR)/share/man/man1/$(BIN).1 installsystemd: @echo using systemd; \ cp ../debian/$(BIN).service /lib/systemd/system/$(BIN).service; \ cp -n ../debian/$(BIN).default /etc/default/$(BIN); \ systemctl daemon-reload; \ systemctl enable $(BIN); \ systemctl start $(BIN); \ installsysv: @echo using sysv; \ cp ../debian/$(BIN).init /etc/init.d/$(BIN); \ cp -n ../debian/$(BIN).default /etc/default/$(BIN); \ update-rc.d $(BIN) defaults; \ /etc/init.d/$(BIN) start; \ adduser: @if ! getent passwd snapclient >/dev/null; then \ useradd --gid audio --system snapclient; \ fi; \ ifeq ($(TARGET), MACOS) uninstall: @launchctl unload /Library/LaunchAgents/de.badaix.snapcast.$(BIN).plist; \ killall -9 $(BIN); \ rm -f $(TARGET_DIR)/local/bin/$(BIN); \ rm -f $(TARGET_DIR)/local/share/man/man1/$(BIN).1; \ rm -f /Library/LaunchAgents/de.badaix.snapcast.$(BIN).plist; \ else uninstall: rm -f $(TARGET_DIR)/share/man/man1/$(BIN).1 @if [[ `systemctl` =~ -\.mount ]]; then \ $(MAKE) uninstallsystemd; \ elif [[ `/sbin/init --version` =~ upstart ]]; then \ $(MAKE) uninstallsysv; \ elif [[ -f /etc/init.d/cron && ! -h /etc/init.d/cron ]]; then \ $(MAKE) uninstallsysv; \ else \ echo cannot tell; \ fi; \ rm -rf /var/run/$(BIN) $(MAKE) deluser endif uninstallsysv: @/etc/init.d/$(BIN) stop; \ killall -9 $(BIN); \ rm -f /usr/bin/$(BIN); \ rm -f /etc/init.d/$(BIN); \ rm -f /etc/default/$(BIN); \ update-rc.d -f $(BIN) remove; \ uninstallsystemd: @systemctl stop $(BIN); \ systemctl disable $(BIN); \ killall -9 $(BIN); \ rm -f /usr/bin/$(BIN); \ rm -f /lib/systemd/system/$(BIN).service; \ rm -f /etc/default/$(BIN); \ systemctl daemon-reload; \ deluser: @userdel --force snapclient > /dev/null || true; \ snapcast-0.18.1/client/browseZeroConf/000077500000000000000000000000001361407301600176435ustar00rootroot00000000000000snapcast-0.18.1/client/browseZeroConf/browse_avahi.cpp000066400000000000000000000172311361407301600230240ustar00rootroot00000000000000/*** This file is part of avahi. avahi is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. avahi 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with avahi; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. ***/ #include "browse_avahi.hpp" #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include #include #include #include #include static AvahiSimplePoll* simple_poll = nullptr; BrowseAvahi::BrowseAvahi() : client_(nullptr), sb_(nullptr) { } BrowseAvahi::~BrowseAvahi() { cleanUp(); } void BrowseAvahi::cleanUp() { if (sb_) avahi_service_browser_free(sb_); sb_ = nullptr; if (client_) avahi_client_free(client_); client_ = nullptr; if (simple_poll) avahi_simple_poll_free(simple_poll); simple_poll = nullptr; } void BrowseAvahi::resolve_callback(AvahiServiceResolver* r, AVAHI_GCC_UNUSED AvahiIfIndex interface, AVAHI_GCC_UNUSED AvahiProtocol protocol, AvahiResolverEvent event, const char* name, const char* type, const char* domain, const char* host_name, const AvahiAddress* address, uint16_t port, AvahiStringList* txt, AvahiLookupResultFlags flags, AVAHI_GCC_UNUSED void* userdata) { BrowseAvahi* browseAvahi = static_cast(userdata); assert(r); /* Called whenever a service has been resolved successfully or timed out */ switch (event) { case AVAHI_RESOLVER_FAILURE: LOG(ERROR) << "(Resolver) Failed to resolve service '" << name << "' of type '" << type << "' in domain '" << domain << "': " << avahi_strerror(avahi_client_errno(avahi_service_resolver_get_client(r))) << "\n"; break; case AVAHI_RESOLVER_FOUND: { char a[AVAHI_ADDRESS_STR_MAX], *t; LOG(INFO) << "Service '" << name << "' of type '" << type << "' in domain '" << domain << "':\n"; avahi_address_snprint(a, sizeof(a), address); browseAvahi->result_.host = host_name; browseAvahi->result_.ip = a; browseAvahi->result_.port = port; // protocol seems to be unreliable (0 for IPv4 and for IPv6) browseAvahi->result_.ip_version = (browseAvahi->result_.ip.find(":") == std::string::npos) ? (IPVersion::IPv4) : (IPVersion::IPv6); browseAvahi->result_.valid = true; browseAvahi->result_.iface_idx = interface; t = avahi_string_list_to_string(txt); LOG(INFO) << "\t" << host_name << ":" << port << " (" << a << ")\n"; LOG(DEBUG) << "\tTXT=" << t << "\n"; LOG(DEBUG) << "\tProto=" << (int)protocol << "\n"; LOG(DEBUG) << "\tcookie is " << avahi_string_list_get_service_cookie(txt) << "\n"; LOG(DEBUG) << "\tis_local: " << !!(flags & AVAHI_LOOKUP_RESULT_LOCAL) << "\n"; LOG(DEBUG) << "\tour_own: " << !!(flags & AVAHI_LOOKUP_RESULT_OUR_OWN) << "\n"; LOG(DEBUG) << "\twide_area: " << !!(flags & AVAHI_LOOKUP_RESULT_WIDE_AREA) << "\n"; LOG(DEBUG) << "\tmulticast: " << !!(flags & AVAHI_LOOKUP_RESULT_MULTICAST) << "\n"; LOG(DEBUG) << "\tcached: " << !!(flags & AVAHI_LOOKUP_RESULT_CACHED) << "\n"; avahi_free(t); } } avahi_service_resolver_free(r); } void BrowseAvahi::browse_callback(AvahiServiceBrowser* b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char* name, const char* type, const char* domain, AVAHI_GCC_UNUSED AvahiLookupResultFlags flags, void* userdata) { // AvahiClient* client = (AvahiClient*)userdata; BrowseAvahi* browseAvahi = static_cast(userdata); assert(b); /* Called whenever a new services becomes available on the LAN or is removed from the LAN */ switch (event) { case AVAHI_BROWSER_FAILURE: LOG(ERROR) << "(Browser) " << avahi_strerror(avahi_client_errno(avahi_service_browser_get_client(b))) << "\n"; avahi_simple_poll_quit(simple_poll); return; case AVAHI_BROWSER_NEW: LOG(INFO) << "(Browser) NEW: service '" << name << "' of type '" << type << "' in domain '" << domain << "'\n"; /* We ignore the returned resolver object. In the callback function we free it. If the server is terminated before the callback function is called the server will free the resolver for us. */ if (!(avahi_service_resolver_new(browseAvahi->client_, interface, protocol, name, type, domain, AVAHI_PROTO_UNSPEC, (AvahiLookupFlags)0, resolve_callback, userdata))) LOG(ERROR) << "Failed to resolve service '" << name << "': " << avahi_strerror(avahi_client_errno(browseAvahi->client_)) << "\n"; break; case AVAHI_BROWSER_REMOVE: LOG(INFO) << "(Browser) REMOVE: service '" << name << "' of type '" << type << "' in domain '" << domain << "'\n"; break; case AVAHI_BROWSER_ALL_FOR_NOW: case AVAHI_BROWSER_CACHE_EXHAUSTED: LOG(INFO) << "(Browser) " << (event == AVAHI_BROWSER_CACHE_EXHAUSTED ? "CACHE_EXHAUSTED" : "ALL_FOR_NOW") << "\n"; break; } } void BrowseAvahi::client_callback(AvahiClient* c, AvahiClientState state, AVAHI_GCC_UNUSED void* userdata) { assert(c); /* Called whenever the client or server state changes */ // BrowseAvahi* browseAvahi = static_cast(userdata); if (state == AVAHI_CLIENT_FAILURE) { LOG(ERROR) << "Server connection failure: " << avahi_strerror(avahi_client_errno(c)) << "\n"; avahi_simple_poll_quit(simple_poll); } } bool BrowseAvahi::browse(const std::string& serviceName, mDNSResult& result, int timeout) { try { /* Allocate main loop object */ if (!(simple_poll = avahi_simple_poll_new())) throw SnapException("BrowseAvahi - Failed to create simple poll object"); /* Allocate a new client */ int error; if (!(client_ = avahi_client_new(avahi_simple_poll_get(simple_poll), (AvahiClientFlags)0, client_callback, this, &error))) throw SnapException("BrowseAvahi - Failed to create client: " + std::string(avahi_strerror(error))); /* Create the service browser */ if (!(sb_ = avahi_service_browser_new(client_, AVAHI_IF_UNSPEC, AVAHI_PROTO_INET, serviceName.c_str(), nullptr, (AvahiLookupFlags)0, browse_callback, this))) throw SnapException("BrowseAvahi - Failed to create service browser: " + std::string(avahi_strerror(avahi_client_errno(client_)))); result_.valid = false; while (timeout > 0) { avahi_simple_poll_iterate(simple_poll, 100); timeout -= 100; if (result_.valid) { result = result_; cleanUp(); return true; } } cleanUp(); return false; } catch (...) { cleanUp(); throw; } } snapcast-0.18.1/client/browseZeroConf/browse_avahi.hpp000066400000000000000000000041651361407301600230330ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef BROWSEAVAHI_H #define BROWSEAVAHI_H #include #include #include #include #include class BrowseAvahi; #include "browse_mdns.hpp" class BrowseAvahi : public BrowsemDNS { public: BrowseAvahi(); ~BrowseAvahi(); bool browse(const std::string& serviceName, mDNSResult& result, int timeout) override; private: void cleanUp(); static void resolve_callback(AvahiServiceResolver* r, AVAHI_GCC_UNUSED AvahiIfIndex interface, AVAHI_GCC_UNUSED AvahiProtocol protocol, AvahiResolverEvent event, const char* name, const char* type, const char* domain, const char* host_name, const AvahiAddress* address, uint16_t port, AvahiStringList* txt, AvahiLookupResultFlags flags, AVAHI_GCC_UNUSED void* userdata); static void browse_callback(AvahiServiceBrowser* b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char* name, const char* type, const char* domain, AVAHI_GCC_UNUSED AvahiLookupResultFlags flags, void* userdata); static void client_callback(AvahiClient* c, AvahiClientState state, AVAHI_GCC_UNUSED void* userdata); AvahiClient* client_; mDNSResult result_; AvahiServiceBrowser* sb_; }; #endif snapcast-0.18.1/client/browseZeroConf/browse_bonjour.cpp000066400000000000000000000202451361407301600234110ustar00rootroot00000000000000#include "browse_bonjour.hpp" #include #include #include #ifdef WINDOWS #include #include #else #include #include #endif #include "common/aixlog.hpp" #include "common/snap_exception.hpp" using namespace std; struct DNSServiceRefDeleter { void operator()(DNSServiceRef* ref) { DNSServiceRefDeallocate(*ref); delete ref; } }; typedef std::unique_ptr DNSServiceHandle; string BonjourGetError(DNSServiceErrorType error) { switch (error) { case kDNSServiceErr_NoError: return "NoError"; default: case kDNSServiceErr_Unknown: return "Unknown"; case kDNSServiceErr_NoSuchName: return "NoSuchName"; case kDNSServiceErr_NoMemory: return "NoMemory"; case kDNSServiceErr_BadParam: return "BadParam"; case kDNSServiceErr_BadReference: return "BadReference"; case kDNSServiceErr_BadState: return "BadState"; case kDNSServiceErr_BadFlags: return "BadFlags"; case kDNSServiceErr_Unsupported: return "Unsupported"; case kDNSServiceErr_NotInitialized: return "NotInitialized"; case kDNSServiceErr_AlreadyRegistered: return "AlreadyRegistered"; case kDNSServiceErr_NameConflict: return "NameConflict"; case kDNSServiceErr_Invalid: return "Invalid"; case kDNSServiceErr_Firewall: return "Firewall"; case kDNSServiceErr_Incompatible: return "Incompatible"; case kDNSServiceErr_BadInterfaceIndex: return "BadInterfaceIndex"; case kDNSServiceErr_Refused: return "Refused"; case kDNSServiceErr_NoSuchRecord: return "NoSuchRecord"; case kDNSServiceErr_NoAuth: return "NoAuth"; case kDNSServiceErr_NoSuchKey: return "NoSuchKey"; case kDNSServiceErr_NATTraversal: return "NATTraversal"; case kDNSServiceErr_DoubleNAT: return "DoubleNAT"; case kDNSServiceErr_BadTime: return "BadTime"; case kDNSServiceErr_BadSig: return "BadSig"; case kDNSServiceErr_BadKey: return "BadKey"; case kDNSServiceErr_Transient: return "Transient"; case kDNSServiceErr_ServiceNotRunning: return "ServiceNotRunning"; case kDNSServiceErr_NATPortMappingUnsupported: return "NATPortMappingUnsupported"; case kDNSServiceErr_NATPortMappingDisabled: return "NATPortMappingDisabled"; case kDNSServiceErr_NoRouter: return "NoRouter"; case kDNSServiceErr_PollingMode: return "PollingMode"; case kDNSServiceErr_Timeout: return "Timeout"; } } struct mDNSReply { string name, regtype, domain; }; struct mDNSResolve { string fullName; uint16_t port; }; #define CHECKED(err) \ if ((err) != kDNSServiceErr_NoError) \ throw SnapException(BonjourGetError(err) + ":" + to_string(__LINE__)); void runService(const DNSServiceHandle& service) { if (!*service) return; auto socket = DNSServiceRefSockFD(*service); fd_set set; FD_ZERO(&set); FD_SET(socket, &set); timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 500000; while (select(FD_SETSIZE, &set, NULL, NULL, &timeout)) { CHECKED(DNSServiceProcessResult(*service)); timeout.tv_sec = 0; timeout.tv_usec = 500000; } } bool BrowseBonjour::browse(const string& serviceName, mDNSResult& result, int /*timeout*/) { result.valid = false; // Discover deque replyCollection; { DNSServiceHandle service(new DNSServiceRef(NULL)); CHECKED(DNSServiceBrowse(service.get(), 0, 0, serviceName.c_str(), "local.", [](DNSServiceRef /*service*/, DNSServiceFlags /*flags*/, uint32_t /*interfaceIndex*/, DNSServiceErrorType errorCode, const char* serviceName, const char* regtype, const char* replyDomain, void* context) { auto replyCollection = static_cast*>(context); CHECKED(errorCode); replyCollection->push_back(mDNSReply{string(serviceName), string(regtype), string(replyDomain)}); }, &replyCollection)); runService(service); } // Resolve deque resolveCollection; { DNSServiceHandle service(new DNSServiceRef(NULL)); for (auto& reply : replyCollection) CHECKED(DNSServiceResolve(service.get(), 0, 0, reply.name.c_str(), reply.regtype.c_str(), reply.domain.c_str(), [](DNSServiceRef /*service*/, DNSServiceFlags /*flags*/, uint32_t /*interfaceIndex*/, DNSServiceErrorType errorCode, const char* /*fullName*/, const char* hosttarget, uint16_t port, uint16_t /*txtLen*/, const unsigned char* /*txtRecord*/, void* context) { auto resultCollection = static_cast*>(context); CHECKED(errorCode); resultCollection->push_back(mDNSResolve{string(hosttarget), ntohs(port)}); }, &resolveCollection)); runService(service); } // DNS/mDNS Resolve deque resultCollection(resolveCollection.size(), mDNSResult{IPVersion::IPv4, 0, "", "", 0, false}); { DNSServiceHandle service(new DNSServiceRef(NULL)); unsigned i = 0; for (auto& resolve : resolveCollection) { resultCollection[i].port = resolve.port; CHECKED(DNSServiceGetAddrInfo(service.get(), kDNSServiceFlagsLongLivedQuery, 0, kDNSServiceProtocol_IPv4, resolve.fullName.c_str(), [](DNSServiceRef /*service*/, DNSServiceFlags /*flags*/, uint32_t interfaceIndex, DNSServiceErrorType /*errorCode*/, const char* hostname, const sockaddr* address, uint32_t /*ttl*/, void* context) { auto result = static_cast(context); result->host = string(hostname); result->ip_version = (address->sa_family == AF_INET) ? (IPVersion::IPv4) : (IPVersion::IPv6); result->iface_idx = static_cast(interfaceIndex); char hostIP[NI_MAXHOST]; char hostService[NI_MAXSERV]; if (getnameinfo(address, sizeof(*address), hostIP, sizeof(hostIP), hostService, sizeof(hostService), NI_NUMERICHOST | NI_NUMERICSERV) == 0) result->ip = string(hostIP); else return; result->valid = true; }, &resultCollection[i++])); } runService(service); } if (resultCollection.size() == 0) return false; if (resultCollection.size() != 1) LOG(NOTICE) << "Multiple servers found. Using first" << endl; result = resultCollection[0]; return true; } #undef CHECKED snapcast-0.18.1/client/browseZeroConf/browse_bonjour.hpp000066400000000000000000000004171361407301600234150ustar00rootroot00000000000000#ifndef BROWSEBONJOUR_H #define BROWSEBONJOUR_H #include class BrowseBonjour; #include "browse_mdns.hpp" class BrowseBonjour : public BrowsemDNS { public: bool browse(const std::string& serviceName, mDNSResult& result, int timeout) override; }; #endif snapcast-0.18.1/client/browseZeroConf/browse_mdns.hpp000066400000000000000000000011031361407301600226710ustar00rootroot00000000000000#ifndef BROWSEMDNS_H #define BROWSEMDNS_H #include enum IPVersion { IPv4 = 0, IPv6 = 1 }; struct mDNSResult { IPVersion ip_version; int iface_idx; std::string ip; std::string host; uint16_t port; bool valid; }; class BrowsemDNS { public: virtual bool browse(const std::string& serviceName, mDNSResult& result, int timeout) = 0; }; #if defined(HAS_AVAHI) #include "browse_avahi.hpp" typedef BrowseAvahi BrowseZeroConf; #elif defined(HAS_BONJOUR) #include "browse_bonjour.hpp" typedef BrowseBonjour BrowseZeroConf; #endif #endif snapcast-0.18.1/client/build_android.sh000077500000000000000000000016731361407301600200410ustar00rootroot00000000000000#/bin/sh if [ -z "$NDK_DIR_ARM" ] && [ -z "$NDK_DIR_ARM64" ] && [ -z "$NDK_DIR_X86" ]; then echo "Specify at least one NDK_DIR_[ARM|ARM64|X86]" exit fi if [ -z "$JNI_LIBS_DIR" ]; then echo "Specify the snapdroid jniLibs dir JNI_LIBS_DIR" exit fi if [ -n "$NDK_DIR_ARM" ]; then export NDK_DIR="$NDK_DIR_ARM" export ARCH=arm make clean; make TARGET=ANDROID -j 4; $NDK_DIR/bin/arm-linux-androideabi-strip ./snapclient; mv ./snapclient "$JNI_LIBS_DIR/armeabi/libsnapclient.so" fi if [ -n "$NDK_DIR_ARM64" ]; then export NDK_DIR="$NDK_DIR_ARM64" export ARCH=arm64 make clean; make TARGET=ANDROID -j 4; $NDK_DIR/bin/aarch64-linux-android-strip ./snapclient; mv ./snapclient "$JNI_LIBS_DIR/arm64-v8a/libsnapclient.so" fi if [ -n "$NDK_DIR_X86" ]; then export NDK_DIR="$NDK_DIR_X86" export ARCH=x86 make clean; make TARGET=ANDROID -j 4; $NDK_DIR/bin/i686-linux-android-strip ./snapclient; mv ./snapclient "$JNI_LIBS_DIR/x86/libsnapclient.so" fi snapcast-0.18.1/client/build_android_all.sh000077500000000000000000000002171361407301600206620ustar00rootroot00000000000000#/bin/sh export NDK_DIR_ARM="$1-arm" export NDK_DIR_ARM64="$1-arm64" export NDK_DIR_X86="$1-x86" export JNI_LIBS_DIR="$2" ./build_android.sh snapcast-0.18.1/client/client_connection.cpp000066400000000000000000000152561361407301600211060ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "client_connection.hpp" #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "message/factory.hpp" #include "message/hello.hpp" #include #include using namespace std; ClientConnection::ClientConnection(MessageReceiver* receiver, const std::string& host, size_t port) : socket_(io_context_), active_(false), messageReceiver_(receiver), reqId_(1), host_(host), port_(port), readerThread_(nullptr), sumTimeout_(chronos::msec(0)) { base_msg_size_ = base_message_.getSize(); buffer_.resize(base_msg_size_); } ClientConnection::~ClientConnection() { stop(); } void ClientConnection::socketRead(void* _to, size_t _bytes) { size_t toRead = _bytes; size_t len = 0; do { len += socket_.read_some(boost::asio::buffer((char*)_to + len, toRead)); // cout << "len: " << len << ", error: " << error << endl; toRead = _bytes - len; } while (toRead > 0); } std::string ClientConnection::getMacAddress() { std::string mac = ::getMacAddress(socket_.native_handle()); if (mac.empty()) mac = "00:00:00:00:00:00"; LOG(INFO) << "My MAC: \"" << mac << "\", socket: " << socket_.native_handle() << "\n"; return mac; } void ClientConnection::start() { tcp::resolver resolver(io_context_); tcp::resolver::query query(host_, cpt::to_string(port_), boost::asio::ip::resolver_query_base::numeric_service); auto iterator = resolver.resolve(query); LOG(DEBUG) << "Connecting\n"; // struct timeval tv; // tv.tv_sec = 5; // tv.tv_usec = 0; // cout << "socket: " << socket->native_handle() << "\n"; // setsockopt(socket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); // setsockopt(socket->native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); socket_.connect(*iterator); SLOG(NOTICE) << "Connected to " << socket_.remote_endpoint().address().to_string() << endl; active_ = true; sumTimeout_ = chronos::msec(0); readerThread_ = new thread(&ClientConnection::reader, this); } void ClientConnection::stop() { active_ = false; try { boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); if (ec) LOG(ERROR) << "Error in socket shutdown: " << ec.message() << endl; socket_.close(ec); if (ec) LOG(ERROR) << "Error in socket close: " << ec.message() << endl; if (readerThread_) { LOG(DEBUG) << "joining readerThread\n"; readerThread_->join(); delete readerThread_; } } catch (...) { } readerThread_ = nullptr; LOG(DEBUG) << "readerThread terminated\n"; } bool ClientConnection::send(const msg::BaseMessage* message) { // std::unique_lock mlock(mutex_); // LOG(DEBUG) << "send: " << message->type << ", size: " << message->getSize() << "\n"; std::lock_guard socketLock(socketMutex_); if (!socket_.is_open()) return false; // LOG(DEBUG) << "send: " << message->type << ", size: " << message->getSize() << "\n"; boost::asio::streambuf streambuf; std::ostream stream(&streambuf); tv t; message->sent = t; message->serialize(stream); boost::asio::write(socket_, streambuf); return true; } unique_ptr ClientConnection::sendRequest(const msg::BaseMessage* message, const chronos::msec& timeout) { unique_ptr response(nullptr); if (++reqId_ >= 10000) reqId_ = 1; message->id = reqId_; // LOG(INFO) << "Req: " << message->id << "\n"; shared_ptr pendingRequest = make_shared(reqId_); { // scope for lock std::unique_lock lock(pendingRequestsMutex_); pendingRequests_.insert(pendingRequest); send(message); } if ((response = pendingRequest->waitForResponse(std::chrono::milliseconds(timeout))) != nullptr) { sumTimeout_ = chronos::msec(0); // LOG(INFO) << "Resp: " << pendingRequest->id << "\n"; } else { sumTimeout_ += timeout; LOG(WARNING) << "timeout while waiting for response to: " << reqId_ << ", timeout " << sumTimeout_.count() << "\n"; if (sumTimeout_ > chronos::sec(10)) throw SnapException("sum timeout exceeded 10s"); } { // scope for lock std::unique_lock lock(pendingRequestsMutex_); pendingRequests_.erase(pendingRequest); } return response; } void ClientConnection::getNextMessage() { socketRead(&buffer_[0], base_msg_size_); base_message_.deserialize(buffer_.data()); // LOG(DEBUG) << "getNextMessage: " << baseMessage.type << ", size: " << baseMessage.size << ", id: " << baseMessage.id << ", refers: " << // baseMessage.refersTo << "\n"; if (base_message_.size > buffer_.size()) buffer_.resize(base_message_.size); // { // std::lock_guard socketLock(socketMutex_); socketRead(buffer_.data(), base_message_.size); tv t; base_message_.received = t; // } { // scope for lock std::unique_lock lock(pendingRequestsMutex_); for (auto req : pendingRequests_) { if (req->id() == base_message_.refersTo) { auto response = msg::factory::createMessage(base_message_, buffer_.data()); req->setValue(std::move(response)); return; } } } if (messageReceiver_ != nullptr) messageReceiver_->onMessageReceived(this, base_message_, buffer_.data()); } void ClientConnection::reader() { try { while (active_) { getNextMessage(); } } catch (const std::exception& e) { if (messageReceiver_ != nullptr) messageReceiver_->onException(this, make_shared(e.what())); } catch (...) { } active_ = false; } snapcast-0.18.1/client/client_connection.hpp000066400000000000000000000106741361407301600211120ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef CLIENT_CONNECTION_H #define CLIENT_CONNECTION_H #include "common/time_defs.hpp" #include "message/message.hpp" #include #include #include #include #include #include #include #include using boost::asio::ip::tcp; class ClientConnection; /// Used to synchronize server requests (wait for server response) class PendingRequest { public: PendingRequest(uint16_t reqId) : id_(reqId) { future_ = promise_.get_future(); }; template std::unique_ptr waitForResponse(const std::chrono::duration& timeout) { try { if (future_.wait_for(timeout) == std::future_status::ready) return future_.get(); } catch (...) { } return nullptr; } void setValue(std::unique_ptr value) { promise_.set_value(std::move(value)); } uint16_t id() const { return id_; } private: uint16_t id_; std::promise> promise_; std::future> future_; }; /// would be nicer to use std::exception_ptr /// but not supported on all plattforms typedef std::shared_ptr shared_exception_ptr; /// Interface: callback for a received message and error reporting class MessageReceiver { public: virtual ~MessageReceiver() = default; virtual void onMessageReceived(ClientConnection* connection, const msg::BaseMessage& baseMessage, char* buffer) = 0; virtual void onException(ClientConnection* connection, shared_exception_ptr exception) = 0; }; /// Endpoint of the server connection /** * Server connection endpoint. * Messages are sent to the server with the "send" method (async). * Messages are sent sync to server with the sendReq method. */ class ClientConnection { public: /// ctor. Received message from the server are passed to MessageReceiver ClientConnection(MessageReceiver* receiver, const std::string& host, size_t port); virtual ~ClientConnection(); virtual void start(); virtual void stop(); virtual bool send(const msg::BaseMessage* message); /// Send request to the server and wait for answer virtual std::unique_ptr sendRequest(const msg::BaseMessage* message, const chronos::msec& timeout = chronos::msec(1000)); /// Send request to the server and wait for answer of type T template std::unique_ptr sendReq(const msg::BaseMessage* message, const chronos::msec& timeout = chronos::msec(1000)) { std::unique_ptr response = sendRequest(message, timeout); if (!response) return nullptr; T* tmp = dynamic_cast(response.get()); std::unique_ptr result; if (tmp != nullptr) { response.release(); result.reset(tmp); } return result; } std::string getMacAddress(); virtual bool active() const { return active_; } protected: virtual void reader(); void socketRead(void* to, size_t bytes); void getNextMessage(); msg::BaseMessage base_message_; std::vector buffer_; size_t base_msg_size_; boost::asio::io_context io_context_; mutable std::mutex socketMutex_; tcp::socket socket_; std::atomic active_; MessageReceiver* messageReceiver_; mutable std::mutex pendingRequestsMutex_; std::set> pendingRequests_; uint16_t reqId_; std::string host_; size_t port_; std::thread* readerThread_; chronos::msec sumTimeout_; }; #endif snapcast-0.18.1/client/controller.cpp000066400000000000000000000223441361407301600175700ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "controller.hpp" #include "decoder/pcm_decoder.hpp" #include #include #include #if defined(HAS_OGG) && (defined(HAS_TREMOR) || defined(HAS_VORBIS)) #include "decoder/ogg_decoder.hpp" #endif #if defined(HAS_FLAC) #include "decoder/flac_decoder.hpp" #endif #if defined(HAS_OPUS) #include "decoder/opus_decoder.hpp" #endif #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "message/hello.hpp" #include "message/time.hpp" #include "time_provider.hpp" using namespace std; Controller::Controller(const std::string& hostId, size_t instance, std::shared_ptr meta) : MessageReceiver(), hostId_(hostId), instance_(instance), active_(false), latency_(0), stream_(nullptr), decoder_(nullptr), player_(nullptr), meta_(meta), serverSettings_(nullptr), async_exception_(nullptr) { } void Controller::onException(ClientConnection* /*connection*/, shared_exception_ptr exception) { LOG(ERROR) << "Controller::onException: " << exception->what() << "\n"; async_exception_ = exception; } void Controller::onMessageReceived(ClientConnection* /*connection*/, const msg::BaseMessage& baseMessage, char* buffer) { std::lock_guard lock(receiveMutex_); if (baseMessage.type == message_type::kWireChunk) { if (stream_ && decoder_) { auto* pcmChunk = new msg::PcmChunk(sampleFormat_, 0); pcmChunk->deserialize(baseMessage, buffer); // LOG(DEBUG) << "chunk: " << pcmChunk->payloadSize << ", sampleFormat: " << sampleFormat_.rate << "\n"; if (decoder_->decode(pcmChunk)) { // TODO: do decoding in thread? stream_->addChunk(pcmChunk); // LOG(DEBUG) << ", decoded: " << pcmChunk->payloadSize << ", Duration: " << pcmChunk->getDuration() << ", sec: " << pcmChunk->timestamp.sec << // ", usec: " << pcmChunk->timestamp.usec/1000 << ", type: " << pcmChunk->type << "\n"; } else delete pcmChunk; } } else if (baseMessage.type == message_type::kTime) { msg::Time reply; reply.deserialize(baseMessage, buffer); TimeProvider::getInstance().setDiff(reply.latency, reply.received - reply.sent); // ToServer(diff / 2); } else if (baseMessage.type == message_type::kServerSettings) { serverSettings_ = make_unique(); serverSettings_->deserialize(baseMessage, buffer); LOG(INFO) << "ServerSettings - buffer: " << serverSettings_->getBufferMs() << ", latency: " << serverSettings_->getLatency() << ", volume: " << serverSettings_->getVolume() << ", muted: " << serverSettings_->isMuted() << "\n"; if (stream_ && player_) { player_->setVolume(serverSettings_->getVolume() / 100.); player_->setMute(serverSettings_->isMuted()); stream_->setBufferLen(serverSettings_->getBufferMs() - serverSettings_->getLatency()); } } else if (baseMessage.type == message_type::kCodecHeader) { headerChunk_ = make_unique(); headerChunk_->deserialize(baseMessage, buffer); LOG(INFO) << "Codec: " << headerChunk_->codec << "\n"; decoder_.reset(nullptr); stream_ = nullptr; player_.reset(nullptr); if (headerChunk_->codec == "pcm") decoder_ = make_unique(); #if defined(HAS_OGG) && (defined(HAS_TREMOR) || defined(HAS_VORBIS)) else if (headerChunk_->codec == "ogg") decoder_ = make_unique(); #endif #if defined(HAS_FLAC) else if (headerChunk_->codec == "flac") decoder_ = make_unique(); #endif #if defined(HAS_OPUS) else if (headerChunk_->codec == "opus") decoder_ = make_unique(); #endif else throw SnapException("codec not supported: \"" + headerChunk_->codec + "\""); sampleFormat_ = decoder_->setHeader(headerChunk_.get()); LOG(NOTICE) << TAG("state") << "sampleformat: " << sampleFormat_.rate << ":" << sampleFormat_.bits << ":" << sampleFormat_.channels << "\n"; stream_ = make_shared(sampleFormat_); stream_->setBufferLen(serverSettings_->getBufferMs() - latency_); #ifdef HAS_ALSA player_ = make_unique(pcmDevice_, stream_); #elif HAS_OPENSL player_ = make_unique(pcmDevice_, stream_); #elif HAS_COREAUDIO player_ = make_unique(pcmDevice_, stream_); #else throw SnapException("No audio player support"); #endif player_->setVolume(serverSettings_->getVolume() / 100.); player_->setMute(serverSettings_->isMuted()); player_->start(); } else if (baseMessage.type == message_type::kStreamTags) { if (meta_) { msg::StreamTags streamTags_; streamTags_.deserialize(baseMessage, buffer); meta_->push(streamTags_.msg); } } if (baseMessage.type != message_type::kTime) if (sendTimeSyncMessage(1000)) LOG(DEBUG) << "time sync onMessageReceived\n"; } bool Controller::sendTimeSyncMessage(long after) { static long lastTimeSync(0); long now = chronos::getTickCount(); if (lastTimeSync + after > now) return false; lastTimeSync = now; msg::Time timeReq; clientConnection_->send(&timeReq); return true; } void Controller::start(const PcmDevice& pcmDevice, const std::string& host, size_t port, int latency) { pcmDevice_ = pcmDevice; latency_ = latency; clientConnection_.reset(new ClientConnection(this, host, port)); controllerThread_ = thread(&Controller::worker, this); } void Controller::run(const PcmDevice& pcmDevice, const std::string& host, size_t port, int latency) { pcmDevice_ = pcmDevice; latency_ = latency; clientConnection_.reset(new ClientConnection(this, host, port)); worker(); // controllerThread_ = thread(&Controller::worker, this); } void Controller::stop() { LOG(DEBUG) << "Stopping Controller" << endl; active_ = false; controllerThread_.join(); clientConnection_->stop(); } void Controller::worker() { active_ = true; while (active_) { try { clientConnection_->start(); string macAddress = clientConnection_->getMacAddress(); if (hostId_.empty()) hostId_ = ::getHostId(macAddress); /// Say hello to the server msg::Hello hello(macAddress, hostId_, instance_); clientConnection_->send(&hello); /// Do initial time sync with the server msg::Time timeReq; for (size_t n = 0; n < 50 && active_; ++n) { if (async_exception_) { LOG(DEBUG) << "Async exception: " << async_exception_->what() << "\n"; throw SnapException(async_exception_->what()); } auto reply = clientConnection_->sendReq(&timeReq, chronos::msec(2000)); if (reply) { TimeProvider::getInstance().setDiff(reply->latency, reply->received - reply->sent); chronos::usleep(100); } } LOG(INFO) << "diff to server [ms]: " << (float)TimeProvider::getInstance().getDiffToServer().count() / 1000.f << "\n"; /// Main loop while (active_) { LOG(DEBUG) << "Main loop\n"; for (size_t n = 0; n < 10 && active_; ++n) { chronos::sleep(100); if (async_exception_) { LOG(DEBUG) << "Async exception: " << async_exception_->what() << "\n"; throw SnapException(async_exception_->what()); } } if (sendTimeSyncMessage(5000)) LOG(DEBUG) << "time sync main loop\n"; } } catch (const std::exception& e) { async_exception_ = nullptr; SLOG(ERROR) << "Exception in Controller::worker(): " << e.what() << endl; clientConnection_->stop(); player_.reset(); stream_.reset(); decoder_.reset(); for (size_t n = 0; (n < 10) && active_; ++n) chronos::sleep(100); } } LOG(DEBUG) << "Thread stopped\n"; } snapcast-0.18.1/client/controller.hpp000066400000000000000000000057021361407301600175740ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef CONTROLLER_H #define CONTROLLER_H #include "decoder/decoder.hpp" #include "message/message.hpp" #include "message/server_settings.hpp" #include "message/stream_tags.hpp" #include "player/pcm_device.hpp" #include #include #ifdef HAS_ALSA #include "player/alsa_player.hpp" #elif HAS_OPENSL #include "player/opensl_player.hpp" #elif HAS_COREAUDIO #include "player/coreaudio_player.hpp" #endif #include "client_connection.hpp" #include "metadata.hpp" #include "stream.hpp" /// Forwards PCM data to the audio player /** * Sets up a connection to the server (using ClientConnection) * Sets up the audio decoder and player. * Decodes audio (message_type::kWireChunk) and feeds PCM to the audio stream buffer * Does timesync with the server */ class Controller : public MessageReceiver { public: Controller(const std::string& clientId, size_t instance, std::shared_ptr meta); void start(const PcmDevice& pcmDevice, const std::string& host, size_t port, int latency); void run(const PcmDevice& pcmDevice, const std::string& host, size_t port, int latency); void stop(); /// Implementation of MessageReceiver. /// ClientConnection passes messages from the server through these callbacks void onMessageReceived(ClientConnection* connection, const msg::BaseMessage& baseMessage, char* buffer) override; /// Implementation of MessageReceiver. /// Used for async exception reporting void onException(ClientConnection* connection, shared_exception_ptr exception) override; private: void worker(); bool sendTimeSyncMessage(long after = 1000); std::string hostId_; std::string meta_callback_; size_t instance_; std::atomic active_; std::thread controllerThread_; SampleFormat sampleFormat_; PcmDevice pcmDevice_; int latency_; std::unique_ptr clientConnection_; std::shared_ptr stream_; std::unique_ptr decoder_; std::unique_ptr player_; std::shared_ptr meta_; std::unique_ptr serverSettings_; std::unique_ptr headerChunk_; std::mutex receiveMutex_; shared_exception_ptr async_exception_; }; #endif snapcast-0.18.1/client/decoder/000077500000000000000000000000001361407301600163015ustar00rootroot00000000000000snapcast-0.18.1/client/decoder/decoder.hpp000066400000000000000000000022371361407301600204230ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef DECODER_H #define DECODER_H #include "common/sample_format.hpp" #include "message/codec_header.hpp" #include "message/pcm_chunk.hpp" #include namespace decoder { class Decoder { public: Decoder(){}; virtual ~Decoder() = default; virtual bool decode(msg::PcmChunk* chunk) = 0; virtual SampleFormat setHeader(msg::CodecHeader* chunk) = 0; protected: std::mutex mutex_; }; } // namespace decoder #endif snapcast-0.18.1/client/decoder/flac_decoder.cpp000066400000000000000000000203121361407301600213750ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "flac_decoder.hpp" #include "common/aixlog.hpp" #include "common/endian.hpp" #include "common/snap_exception.hpp" #include #include #include using namespace std; namespace decoder { namespace callback { FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder* decoder, FLAC__byte buffer[], size_t* bytes, void* client_data); FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder* decoder, const FLAC__Frame* frame, const FLAC__int32* const buffer[], void* client_data); void metadata_callback(const FLAC__StreamDecoder* decoder, const FLAC__StreamMetadata* metadata, void* client_data); void error_callback(const FLAC__StreamDecoder* decoder, FLAC__StreamDecoderErrorStatus status, void* client_data); } // namespace callback namespace { msg::CodecHeader* flacHeader = nullptr; msg::PcmChunk* flacChunk = nullptr; msg::PcmChunk* pcmChunk = nullptr; SampleFormat sampleFormat; FLAC__StreamDecoder* decoder = nullptr; } // namespace FlacDecoder::FlacDecoder() : Decoder(), lastError_(nullptr) { flacChunk = new msg::PcmChunk(); } FlacDecoder::~FlacDecoder() { std::lock_guard lock(mutex_); FLAC__stream_decoder_delete(decoder); delete flacChunk; } bool FlacDecoder::decode(msg::PcmChunk* chunk) { std::lock_guard lock(mutex_); cacheInfo_.reset(); pcmChunk = chunk; flacChunk->payload = (char*)realloc(flacChunk->payload, chunk->payloadSize); memcpy(flacChunk->payload, chunk->payload, chunk->payloadSize); flacChunk->payloadSize = chunk->payloadSize; pcmChunk->payload = (char*)realloc(pcmChunk->payload, 0); pcmChunk->payloadSize = 0; while (flacChunk->payloadSize > 0) { if (!FLAC__stream_decoder_process_single(decoder)) { return false; } if (lastError_) { LOG(ERROR) << "FLAC decode error: " << FLAC__StreamDecoderErrorStatusString[*lastError_] << "\n"; lastError_ = nullptr; return false; } } if ((cacheInfo_.cachedBlocks_ > 0) && (cacheInfo_.sampleRate_ != 0)) { double diffMs = cacheInfo_.cachedBlocks_ / ((double)cacheInfo_.sampleRate_ / 1000.); int32_t s = (diffMs / 1000); int32_t us = (diffMs * 1000); us %= 1000000; LOG(DEBUG) << "Cached: " << cacheInfo_.cachedBlocks_ << ", " << diffMs << "ms, " << s << "s, " << us << "us\n"; chunk->timestamp = chunk->timestamp - tv(s, us); } return true; } SampleFormat FlacDecoder::setHeader(msg::CodecHeader* chunk) { flacHeader = chunk; FLAC__StreamDecoderInitStatus init_status; if ((decoder = FLAC__stream_decoder_new()) == nullptr) throw SnapException("ERROR: allocating decoder"); // (void)FLAC__stream_decoder_set_md5_checking(decoder, true); init_status = FLAC__stream_decoder_init_stream(decoder, callback::read_callback, nullptr, nullptr, nullptr, nullptr, callback::write_callback, callback::metadata_callback, callback::error_callback, this); if (init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) throw SnapException("ERROR: initializing decoder: " + string(FLAC__StreamDecoderInitStatusString[init_status])); sampleFormat.rate = 0; FLAC__stream_decoder_process_until_end_of_metadata(decoder); if (sampleFormat.rate == 0) throw SnapException("Sample format not found"); return sampleFormat; } namespace callback { FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder* /*decoder*/, FLAC__byte buffer[], size_t* bytes, void* client_data) { if (flacHeader != nullptr) { *bytes = flacHeader->payloadSize; memcpy(buffer, flacHeader->payload, *bytes); flacHeader = nullptr; } else if (flacChunk != nullptr) { // cerr << "read_callback: " << *bytes << ", avail: " << flacChunk->payloadSize << "\n"; static_cast(client_data)->cacheInfo_.isCachedChunk_ = false; if (*bytes > flacChunk->payloadSize) *bytes = flacChunk->payloadSize; // if (*bytes == 0) // return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; memcpy(buffer, flacChunk->payload, *bytes); memmove(flacChunk->payload, flacChunk->payload + *bytes, flacChunk->payloadSize - *bytes); flacChunk->payloadSize = flacChunk->payloadSize - *bytes; flacChunk->payload = (char*)realloc(flacChunk->payload, flacChunk->payloadSize); } return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; } FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder* /*decoder*/, const FLAC__Frame* frame, const FLAC__int32* const buffer[], void* client_data) { if (pcmChunk != nullptr) { size_t bytes = frame->header.blocksize * sampleFormat.frameSize; FlacDecoder* flacDecoder = static_cast(client_data); if (flacDecoder->cacheInfo_.isCachedChunk_) flacDecoder->cacheInfo_.cachedBlocks_ += frame->header.blocksize; pcmChunk->payload = (char*)realloc(pcmChunk->payload, pcmChunk->payloadSize + bytes); for (size_t channel = 0; channel < sampleFormat.channels; ++channel) { if (buffer[channel] == nullptr) { SLOG(ERROR) << "ERROR: buffer[" << channel << "] is NULL\n"; return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; } if (sampleFormat.sampleSize == 1) { int8_t* chunkBuffer = (int8_t*)(pcmChunk->payload + pcmChunk->payloadSize); for (size_t i = 0; i < frame->header.blocksize; i++) chunkBuffer[sampleFormat.channels * i + channel] = (int8_t)(buffer[channel][i]); } else if (sampleFormat.sampleSize == 2) { int16_t* chunkBuffer = (int16_t*)(pcmChunk->payload + pcmChunk->payloadSize); for (size_t i = 0; i < frame->header.blocksize; i++) chunkBuffer[sampleFormat.channels * i + channel] = SWAP_16((int16_t)(buffer[channel][i])); } else if (sampleFormat.sampleSize == 4) { int32_t* chunkBuffer = (int32_t*)(pcmChunk->payload + pcmChunk->payloadSize); for (size_t i = 0; i < frame->header.blocksize; i++) chunkBuffer[sampleFormat.channels * i + channel] = SWAP_32((int32_t)(buffer[channel][i])); } } pcmChunk->payloadSize += bytes; } return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; } void metadata_callback(const FLAC__StreamDecoder* /*decoder*/, const FLAC__StreamMetadata* metadata, void* client_data) { /* print some stats */ if (metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { static_cast(client_data)->cacheInfo_.sampleRate_ = metadata->data.stream_info.sample_rate; sampleFormat.setFormat(metadata->data.stream_info.sample_rate, metadata->data.stream_info.bits_per_sample, metadata->data.stream_info.channels); } } void error_callback(const FLAC__StreamDecoder* /*decoder*/, FLAC__StreamDecoderErrorStatus status, void* client_data) { SLOG(ERROR) << "Got error callback: " << FLAC__StreamDecoderErrorStatusString[status] << "\n"; static_cast(client_data)->lastError_ = std::unique_ptr(new FLAC__StreamDecoderErrorStatus(status)); } } // namespace callback } // namespace decoder snapcast-0.18.1/client/decoder/flac_decoder.hpp000066400000000000000000000027121361407301600214060ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef FLAC_DECODER_H #define FLAC_DECODER_H #include "decoder.hpp" #include #include #include namespace decoder { struct CacheInfo { CacheInfo() : sampleRate_(0) { reset(); } void reset() { isCachedChunk_ = true; cachedBlocks_ = 0; } bool isCachedChunk_; size_t cachedBlocks_; size_t sampleRate_; }; class FlacDecoder : public Decoder { public: FlacDecoder(); ~FlacDecoder() override; bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; CacheInfo cacheInfo_; std::unique_ptr lastError_; }; } // namespace decoder #endif snapcast-0.18.1/client/decoder/ogg_decoder.cpp000066400000000000000000000207341361407301600212540ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include #include #include #include "common/aixlog.hpp" #include "common/endian.hpp" #include "common/snap_exception.hpp" #include "ogg_decoder.hpp" using namespace std; namespace decoder { OggDecoder::OggDecoder() : Decoder() { ogg_sync_init(&oy); /* Now we can read pages */ } OggDecoder::~OggDecoder() { std::lock_guard lock(mutex_); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); ogg_stream_clear(&os); vorbis_comment_clear(&vc); vorbis_info_clear(&vi); /* must be called last */ ogg_sync_clear(&oy); } bool OggDecoder::decode(msg::PcmChunk* chunk) { std::lock_guard lock(mutex_); /* grab some data at the head of the stream. We want the first page (which is guaranteed to be small and only contain the Vorbis stream initial header) We need the first page to get the stream serialno. */ int size = chunk->payloadSize; char* buffer = ogg_sync_buffer(&oy, size); memcpy(buffer, chunk->payload, size); ogg_sync_wrote(&oy, size); chunk->payloadSize = 0; /* The rest is just a straight decode loop until end of stream */ // while(!eos){ while (true) { int result = ogg_sync_pageout(&oy, &og); if (result == 0) break; /* need more data */ if (result < 0) { /* missing or corrupt data at this page position */ LOG(ERROR) << "Corrupt or missing data in bitstream; continuing...\n"; continue; } ogg_stream_pagein(&os, &og); /* can safely ignore errors at this point */ while (1) { result = ogg_stream_packetout(&os, &op); if (result == 0) break; /* need more data */ if (result < 0) continue; /* missing or corrupt data at this page position */ /* no reason to complain; already complained above */ /* we have a packet. Decode it */ #ifdef HAS_TREMOR ogg_int32_t** pcm; #else float** pcm; #endif int samples; if (vorbis_synthesis(&vb, &op) == 0) /* test for success! */ vorbis_synthesis_blockin(&vd, &vb); /* **pcm is a multichannel float vector. In stereo, for example, pcm[0] is left, and pcm[1] is right. samples is the size of each channel. Convert the float values (-1.<=range<=1.) to whatever PCM format and write it out */ while ((samples = vorbis_synthesis_pcmout(&vd, &pcm)) > 0) { size_t bytes = sampleFormat_.sampleSize * vi.channels * samples; chunk->payload = (char*)realloc(chunk->payload, chunk->payloadSize + bytes); for (int channel = 0; channel < vi.channels; ++channel) { if (sampleFormat_.sampleSize == 1) { int8_t* chunkBuffer = (int8_t*)(chunk->payload + chunk->payloadSize); for (int i = 0; i < samples; i++) { int8_t& val = chunkBuffer[sampleFormat_.channels * i + channel]; #ifdef HAS_TREMOR val = clip(pcm[channel][i], -128, 127); #else val = clip(floor(pcm[channel][i] * 127.f + .5f), -128, 127); #endif } } else if (sampleFormat_.sampleSize == 2) { int16_t* chunkBuffer = (int16_t*)(chunk->payload + chunk->payloadSize); for (int i = 0; i < samples; i++) { int16_t& val = chunkBuffer[sampleFormat_.channels * i + channel]; #ifdef HAS_TREMOR val = SWAP_16(clip(pcm[channel][i] >> 9, -32768, 32767)); #else val = SWAP_16(clip(floor(pcm[channel][i] * 32767.f + .5f), -32768, 32767)); #endif } } else if (sampleFormat_.sampleSize == 4) { int32_t* chunkBuffer = (int32_t*)(chunk->payload + chunk->payloadSize); for (int i = 0; i < samples; i++) { int32_t& val = chunkBuffer[sampleFormat_.channels * i + channel]; #ifdef HAS_TREMOR val = SWAP_32(clip(pcm[channel][i] << 7, -2147483648, 2147483647)); #else val = SWAP_32(clip(floor(pcm[channel][i] * 2147483647.f + .5f), -2147483648, 2147483647)); #endif } } } chunk->payloadSize += bytes; vorbis_synthesis_read(&vd, samples); } } } return true; } SampleFormat OggDecoder::setHeader(msg::CodecHeader* chunk) { int size = chunk->payloadSize; char* buffer = ogg_sync_buffer(&oy, size); memcpy(buffer, chunk->payload, size); ogg_sync_wrote(&oy, size); if (ogg_sync_pageout(&oy, &og) != 1) throw SnapException("Input does not appear to be an Ogg bitstream"); ogg_stream_init(&os, ogg_page_serialno(&og)); vorbis_info_init(&vi); vorbis_comment_init(&vc); if (ogg_stream_pagein(&os, &og) < 0) throw SnapException("Error reading first page of Ogg bitstream data"); if (ogg_stream_packetout(&os, &op) != 1) throw SnapException("Error reading initial header packet"); if (vorbis_synthesis_headerin(&vi, &vc, &op) < 0) throw SnapException("This Ogg bitstream does not contain Vorbis audio data"); int i(0); while (i < 2) { while (i < 2) { int result = ogg_sync_pageout(&oy, &og); if (result == 0) break; /* Need more data */ /* Don't complain about missing or corrupt data yet. We'll catch it at the packet output phase */ if (result == 1) { ogg_stream_pagein(&os, &og); /* we can ignore any errors here as they'll also become apparent at packetout */ while (i < 2) { result = ogg_stream_packetout(&os, &op); if (result == 0) break; /// Uh oh; data at some point was corrupted or missing! /// We can't tolerate that in a header. Die. */ if (result < 0) throw SnapException("Corrupt secondary header. Exiting."); result = vorbis_synthesis_headerin(&vi, &vc, &op); if (result < 0) throw SnapException("Corrupt secondary header. Exiting."); i++; } } } } /// OK, got and parsed all three headers. Initialize the Vorbis packet->PCM decoder. if (vorbis_synthesis_init(&vd, &vi) == 0) vorbis_block_init(&vd, &vb); /// central decode state /// local state for most of the decode so multiple block decodes can proceed /// in parallel. We could init multiple vorbis_block structures for vd here sampleFormat_.setFormat(vi.rate, 16, vi.channels); /* Throw the comments plus a few lines about the bitstream we're decoding */ char** ptr = vc.user_comments; while (*ptr) { std::string comment(*ptr); if (comment.find("SAMPLE_FORMAT=") == 0) sampleFormat_.setFormat(comment.substr(comment.find("=") + 1)); LOG(INFO) << "comment: " << comment << "\n"; ; ++ptr; } LOG(INFO) << "Encoded by: " << vc.vendor << "\n"; return sampleFormat_; } } // namespace decoder snapcast-0.18.1/client/decoder/ogg_decoder.hpp000066400000000000000000000041111361407301600212500ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef OGG_DECODER_H #define OGG_DECODER_H #include "decoder.hpp" #ifdef HAS_TREMOR #include #else #include #endif #include namespace decoder { class OggDecoder : public Decoder { public: OggDecoder(); ~OggDecoder() override; bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; private: bool decodePayload(msg::PcmChunk* chunk); template T clip(const T& value, const T& lower, const T& upper) const { if (value > upper) return upper; if (value < lower) return lower; return value; } ogg_sync_state oy; /// sync and verify incoming physical bitstream ogg_stream_state os; /// take physical pages, weld into a logical stream of packets ogg_page og; /// one Ogg bitstream page. Vorbis packets are inside ogg_packet op; /// one raw packet of data for decode vorbis_info vi; /// struct that stores all the static vorbis bitstream settings vorbis_comment vc; /// struct that stores all the bitstream user comments vorbis_dsp_state vd; /// central working state for the packet->PCM decoder vorbis_block vb; /// local working space for packet->PCM decode SampleFormat sampleFormat_; }; } // namespace decoder #endif snapcast-0.18.1/client/decoder/opus_decoder.cpp000066400000000000000000000075731361407301600214740ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2015 Hannes Ellinger 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 3 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 . ***/ #include "opus_decoder.hpp" #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" namespace decoder { #define ID_OPUS 0x4F505553 /// int: Number of samples per channel in the input signal. /// This must be an Opus frame size for the encoder's sampling rate. For example, at 48 kHz the /// permitted values are 120, 240, 480, 960, 1920, and 2880. /// Passing in a duration of less than 10 ms (480 samples at 48 kHz) will prevent the encoder from using the LPC or hybrid modes. static constexpr int const_max_frame_size = 2880; OpusDecoder::OpusDecoder() : Decoder(), dec_(nullptr) { pcm_.resize(120); } OpusDecoder::~OpusDecoder() { if (dec_ != nullptr) opus_decoder_destroy(dec_); } bool OpusDecoder::decode(msg::PcmChunk* chunk) { int frame_size = 0; while ((frame_size = opus_decode(dec_, (unsigned char*)chunk->payload, chunk->payloadSize, pcm_.data(), pcm_.size() / sample_format_.channels, 0)) == OPUS_BUFFER_TOO_SMALL) { if (pcm_.size() < const_max_frame_size * sample_format_.channels) { pcm_.resize(pcm_.size() * 2); LOG(INFO) << "OPUS encoding buffer too small, resizing to " << pcm_.size() / sample_format_.channels << " samples per channel\n"; } else break; } if (frame_size < 0) { LOG(ERROR) << "Failed to decode chunk: " << opus_strerror(frame_size) << ", IN size: " << chunk->payloadSize << ", OUT size: " << pcm_.size() << '\n'; return false; } else { LOG(DEBUG) << "Decoded chunk: size " << chunk->payloadSize << " bytes, decoded " << frame_size << " samples" << '\n'; // copy encoded data to chunk chunk->payloadSize = frame_size * sample_format_.channels * sizeof(opus_int16); chunk->payload = (char*)realloc(chunk->payload, chunk->payloadSize); memcpy(chunk->payload, (char*)pcm_.data(), chunk->payloadSize); return true; } } SampleFormat OpusDecoder::setHeader(msg::CodecHeader* chunk) { // decode the opus pseudo header if (chunk->payloadSize < 12) throw SnapException("OPUS header too small"); // decode the "opus id" magic number, this is our constant part that must match uint32_t id_opus; memcpy(&id_opus, chunk->payload, sizeof(id_opus)); if (SWAP_32(id_opus) != ID_OPUS) throw SnapException("Not an Opus pseudo header"); // decode the sampleformat uint32_t rate; memcpy(&rate, chunk->payload + 4, sizeof(id_opus)); uint16_t bits; memcpy(&bits, chunk->payload + 8, sizeof(bits)); uint16_t channels; memcpy(&channels, chunk->payload + 10, sizeof(channels)); sample_format_.setFormat(SWAP_32(rate), SWAP_16(bits), SWAP_16(channels)); LOG(DEBUG) << "Opus sampleformat: " << sample_format_.getFormat() << "\n"; // create the decoder int error; dec_ = opus_decoder_create(sample_format_.rate, sample_format_.channels, &error); if (error != 0) throw SnapException("Failed to initialize Opus decoder: " + std::string(opus_strerror(error))); return sample_format_; } } // namespace decoder snapcast-0.18.1/client/decoder/opus_decoder.hpp000066400000000000000000000022571361407301600214730ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2015 Hannes Ellinger 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 3 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 . ***/ #pragma once #include "decoder/decoder.hpp" #include namespace decoder { class OpusDecoder : public Decoder { public: OpusDecoder(); ~OpusDecoder(); bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; private: ::OpusDecoder* dec_; std::vector pcm_; SampleFormat sample_format_; }; } // namespace decoder snapcast-0.18.1/client/decoder/pcm_decoder.cpp000066400000000000000000000067351361407301600212640ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "pcm_decoder.hpp" #include "common/aixlog.hpp" #include "common/endian.hpp" #include "common/snap_exception.hpp" namespace decoder { #define ID_RIFF 0x46464952 #define ID_WAVE 0x45564157 #define ID_FMT 0x20746d66 #define ID_DATA 0x61746164 struct riff_wave_header { uint32_t riff_id; uint32_t riff_sz; uint32_t wave_id; }; struct chunk_header { uint32_t id; uint32_t sz; }; struct chunk_fmt { uint16_t audio_format; uint16_t num_channels; uint32_t sample_rate; uint32_t byte_rate; uint16_t block_align; uint16_t bits_per_sample; }; PcmDecoder::PcmDecoder() : Decoder() { } bool PcmDecoder::decode(msg::PcmChunk* /*chunk*/) { return true; } SampleFormat PcmDecoder::setHeader(msg::CodecHeader* chunk) { if (chunk->payloadSize < 44) throw SnapException("PCM header too small"); struct riff_wave_header riff_wave_header; struct chunk_header chunk_header; struct chunk_fmt chunk_fmt; chunk_fmt.sample_rate = SWAP_32(0); chunk_fmt.bits_per_sample = SWAP_16(0); chunk_fmt.num_channels = SWAP_16(0); size_t pos(0); memcpy(&riff_wave_header, chunk->payload + pos, sizeof(riff_wave_header)); pos += sizeof(riff_wave_header); if ((SWAP_32(riff_wave_header.riff_id) != ID_RIFF) || (SWAP_32(riff_wave_header.wave_id) != ID_WAVE)) throw SnapException("Not a riff/wave header"); bool moreChunks(true); do { if (pos + sizeof(chunk_header) > chunk->payloadSize) throw SnapException("riff/wave header incomplete"); memcpy(&chunk_header, chunk->payload + pos, sizeof(chunk_header)); pos += sizeof(chunk_header); switch (SWAP_32(chunk_header.id)) { case ID_FMT: if (pos + sizeof(chunk_fmt) > chunk->payloadSize) throw SnapException("riff/wave header incomplete"); memcpy(&chunk_fmt, chunk->payload + pos, sizeof(chunk_fmt)); pos += sizeof(chunk_fmt); /// If the format header is larger, skip the rest if (SWAP_32(chunk_header.sz) > sizeof(chunk_fmt)) pos += (SWAP_32(chunk_header.sz) - sizeof(chunk_fmt)); break; case ID_DATA: /// Stop looking for chunks moreChunks = false; break; default: /// Unknown chunk, skip bytes pos += SWAP_32(chunk_header.sz); } } while (moreChunks); if (SWAP_32(chunk_fmt.sample_rate) == 0) throw SnapException("Sample format not found"); SampleFormat sampleFormat(SWAP_32(chunk_fmt.sample_rate), SWAP_16(chunk_fmt.bits_per_sample), SWAP_16(chunk_fmt.num_channels)); return sampleFormat; } } // namespace decoder snapcast-0.18.1/client/decoder/pcm_decoder.hpp000066400000000000000000000020161361407301600212550ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef PCM_DECODER_H #define PCM_DECODER_H #include "decoder.hpp" namespace decoder { class PcmDecoder : public Decoder { public: PcmDecoder(); bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; }; } // namespace decoder #endif snapcast-0.18.1/client/double_buffer.hpp000066400000000000000000000062231361407301600202130ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef DOUBLE_BUFFER_H #define DOUBLE_BUFFER_H #include #include /// Size limited queue /** * Size limited queue with basic statistic functions: * median, mean, percentile */ template class DoubleBuffer { public: DoubleBuffer(size_t size = 10) : bufferSize(size) { } inline void add(const T& element) { buffer.push_back(element); if (buffer.size() > bufferSize) buffer.pop_front(); } inline void add(T&& element) { buffer.push_back(std::move(element)); if (buffer.size() > bufferSize) buffer.pop_front(); } /// Median as mean over N values around the median T median(unsigned int mean = 1) const { if (buffer.empty()) return 0; std::deque tmpBuffer(buffer.begin(), buffer.end()); std::sort(tmpBuffer.begin(), tmpBuffer.end()); if ((mean <= 1) || (tmpBuffer.size() < mean)) return tmpBuffer[tmpBuffer.size() / 2]; else { unsigned int low = tmpBuffer.size() / 2; unsigned int high = low; low -= mean / 2; high += mean / 2; T result((T)0); for (unsigned int i = low; i <= high; ++i) { result += tmpBuffer[i]; } return result / mean; } } double mean() const { if (buffer.empty()) return 0; double mean = 0.; for (size_t n = 0; n < buffer.size(); ++n) mean += (float)buffer[n] / (float)buffer.size(); return mean; } T percentile(unsigned int percentile) const { if (buffer.empty()) return 0; std::deque tmpBuffer(buffer.begin(), buffer.end()); std::sort(tmpBuffer.begin(), tmpBuffer.end()); return tmpBuffer[(size_t)(tmpBuffer.size() * ((float)percentile / (float)100))]; } inline bool full() const { return (buffer.size() == bufferSize); } inline void clear() { buffer.clear(); } inline size_t size() const { return buffer.size(); } inline bool empty() const { return (buffer.size() == 0); } void setSize(size_t size) { bufferSize = size; } const std::deque& getBuffer() const { return &buffer; } private: size_t bufferSize; std::deque buffer; }; #endif snapcast-0.18.1/client/etc/000077500000000000000000000000001361407301600154475ustar00rootroot00000000000000snapcast-0.18.1/client/etc/snapclient.plist000066400000000000000000000007031361407301600206640ustar00rootroot00000000000000 Label de.badaix.snapcast.snapclient ProgramArguments /usr/local/bin/snapclient RunAtLoad KeepAlive snapcast-0.18.1/client/metadata.hpp000066400000000000000000000037701361407301600171740ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef METADATA_H #define METADATA_H #include "common/json.hpp" // Prefix used in output #define METADATA std::string("metadata") /* * Implement a generic metadata output handler */ using json = nlohmann::json; /* * Base class, prints to stdout */ class MetadataAdapter { public: MetadataAdapter() { reset(); } virtual ~MetadataAdapter() = default; void reset() { msg_ = json{}; } std::string serialize() { return METADATA + ":" + msg_.dump(); } void tag(const std::string& name, const std::string& value) { msg_[name] = value; } std::string operator[](const std::string& key) { try { return msg_[key]; } catch (std::domain_error&) { return std::string(); } } virtual int push() { std::cout << serialize() << "\n"; return 0; } int push(const json& jtag) { msg_ = jtag; return push(); } protected: json msg_; }; /* * Send metadata to stderr as json */ class MetaStderrAdapter : public MetadataAdapter { public: using MetadataAdapter::push; int push() override { std::cerr << serialize() << "\n"; return 0; } }; #endif snapcast-0.18.1/client/player/000077500000000000000000000000001361407301600161705ustar00rootroot00000000000000snapcast-0.18.1/client/player/alsa_player.cpp000066400000000000000000000224721361407301600211770ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "alsa_player.hpp" #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" //#define BUFFER_TIME 120000 #define PERIOD_TIME 30000 using namespace std; AlsaPlayer::AlsaPlayer(const PcmDevice& pcmDevice, std::shared_ptr stream) : Player(pcmDevice, stream), handle_(nullptr), buff_(nullptr) { } void AlsaPlayer::initAlsa() { unsigned int tmp, rate; int pcm, channels; snd_pcm_hw_params_t* params; int buff_size; const SampleFormat& format = stream_->getFormat(); rate = format.rate; channels = format.channels; /* Open the PCM device in playback mode */ if ((pcm = snd_pcm_open(&handle_, pcmDevice_.name.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) throw SnapException("Can't open " + pcmDevice_.name + " PCM device: " + snd_strerror(pcm)); /* struct snd_pcm_playback_info_t pinfo; if ( (pcm = snd_pcm_playback_info( pcm_handle, &pinfo )) < 0 ) fprintf( stderr, "Error: playback info error: %s\n", snd_strerror( err ) ); printf("buffer: '%d'\n", pinfo.buffer_size); */ /* Allocate parameters object and fill it with default values*/ snd_pcm_hw_params_alloca(¶ms); if ((pcm = snd_pcm_hw_params_any(handle_, params)) < 0) throw SnapException("Can't fill params: " + string(snd_strerror(pcm))); /* Set parameters */ if ((pcm = snd_pcm_hw_params_set_access(handle_, params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) throw SnapException("Can't set interleaved mode: " + string(snd_strerror(pcm))); snd_pcm_format_t snd_pcm_format; if (format.bits == 8) snd_pcm_format = SND_PCM_FORMAT_S8; else if (format.bits == 16) snd_pcm_format = SND_PCM_FORMAT_S16_LE; else if ((format.bits == 24) && (format.sampleSize == 4)) snd_pcm_format = SND_PCM_FORMAT_S24_LE; else if (format.bits == 32) snd_pcm_format = SND_PCM_FORMAT_S32_LE; else throw SnapException("Unsupported sample format: " + cpt::to_string(format.bits)); pcm = snd_pcm_hw_params_set_format(handle_, params, snd_pcm_format); if (pcm == -EINVAL) { if (snd_pcm_format == SND_PCM_FORMAT_S24_LE) { snd_pcm_format = SND_PCM_FORMAT_S32_LE; volCorrection_ = 256; } if (snd_pcm_format == SND_PCM_FORMAT_S8) { snd_pcm_format = SND_PCM_FORMAT_U8; } } pcm = snd_pcm_hw_params_set_format(handle_, params, snd_pcm_format); if (pcm < 0) { cerr << "error: " << pcm << "\n"; stringstream ss; ss << "Can't set format: " << string(snd_strerror(pcm)) << ", supported: "; for (int format = 0; format <= (int)SND_PCM_FORMAT_LAST; format++) { snd_pcm_format_t snd_pcm_format = static_cast(format); if (snd_pcm_hw_params_test_format(handle_, params, snd_pcm_format) == 0) ss << snd_pcm_format_name(snd_pcm_format) << " "; } throw SnapException(ss.str()); } if ((pcm = snd_pcm_hw_params_set_channels(handle_, params, channels)) < 0) throw SnapException("Can't set channels number: " + string(snd_strerror(pcm))); if ((pcm = snd_pcm_hw_params_set_rate_near(handle_, params, &rate, nullptr)) < 0) throw SnapException("Can't set rate: " + string(snd_strerror(pcm))); unsigned int period_time; snd_pcm_hw_params_get_period_time_max(params, &period_time, nullptr); if (period_time > PERIOD_TIME) period_time = PERIOD_TIME; unsigned int buffer_time = 4 * period_time; snd_pcm_hw_params_set_period_time_near(handle_, params, &period_time, nullptr); snd_pcm_hw_params_set_buffer_time_near(handle_, params, &buffer_time, nullptr); // long unsigned int periodsize = stream_->format.msRate() * 50;//2*rate/50; // if ((pcm = snd_pcm_hw_params_set_buffer_size_near(pcm_handle, params, &periodsize)) < 0) // LOG(ERROR) << "Unable to set buffer size " << (long int)periodsize << ": " << snd_strerror(pcm) << "\n"; /* Write parameters */ if ((pcm = snd_pcm_hw_params(handle_, params)) < 0) throw SnapException("Can't set harware parameters: " + string(snd_strerror(pcm))); /* Resume information */ LOG(DEBUG) << "PCM name: " << snd_pcm_name(handle_) << "\n"; LOG(DEBUG) << "PCM state: " << snd_pcm_state_name(snd_pcm_state(handle_)) << "\n"; snd_pcm_hw_params_get_channels(params, &tmp); LOG(DEBUG) << "channels: " << tmp << "\n"; snd_pcm_hw_params_get_rate(params, &tmp, nullptr); LOG(DEBUG) << "rate: " << tmp << " bps\n"; /* Allocate buffer to hold single period */ snd_pcm_hw_params_get_period_size(params, &frames_, nullptr); LOG(INFO) << "frames: " << frames_ << "\n"; buff_size = frames_ * format.frameSize; // channels * 2 /* 2 -> sample size */; buff_ = (char*)malloc(buff_size); snd_pcm_hw_params_get_period_time(params, &tmp, nullptr); LOG(DEBUG) << "period time: " << tmp << "\n"; snd_pcm_sw_params_t* swparams; snd_pcm_sw_params_alloca(&swparams); snd_pcm_sw_params_current(handle_, swparams); snd_pcm_sw_params_set_avail_min(handle_, swparams, frames_); snd_pcm_sw_params_set_start_threshold(handle_, swparams, frames_); // snd_pcm_sw_params_set_stop_threshold(pcm_handle, swparams, frames_); snd_pcm_sw_params(handle_, swparams); } void AlsaPlayer::uninitAlsa() { if (handle_ != nullptr) { snd_pcm_drain(handle_); snd_pcm_close(handle_); handle_ = nullptr; } if (buff_ != nullptr) { free(buff_); buff_ = nullptr; } } void AlsaPlayer::start() { initAlsa(); Player::start(); } AlsaPlayer::~AlsaPlayer() { stop(); } void AlsaPlayer::stop() { Player::stop(); uninitAlsa(); } void AlsaPlayer::worker() { snd_pcm_sframes_t pcm; snd_pcm_sframes_t framesDelay; long lastChunkTick = chronos::getTickCount(); while (active_) { if (handle_ == nullptr) { try { initAlsa(); } catch (const std::exception& e) { LOG(ERROR) << "Exception in initAlsa: " << e.what() << endl; chronos::sleep(100); } } // snd_pcm_avail_delay(handle_, &framesAvail, &framesDelay); snd_pcm_delay(handle_, &framesDelay); chronos::usec delay((chronos::usec::rep)(1000 * (double)framesDelay / stream_->getFormat().msRate())); // LOG(INFO) << "delay: " << framesDelay << ", delay[ms]: " << delay.count() / 1000 << "\n"; if (stream_->getPlayerChunk(buff_, delay, frames_)) { lastChunkTick = chronos::getTickCount(); adjustVolume(buff_, frames_); if ((pcm = snd_pcm_writei(handle_, buff_, frames_)) == -EPIPE) { LOG(ERROR) << "XRUN: " << snd_strerror(pcm) << "\n"; snd_pcm_prepare(handle_); } else if (pcm < 0) { LOG(ERROR) << "ERROR. Can't write to PCM device: " << snd_strerror(pcm) << "\n"; uninitAlsa(); } } else { LOG(INFO) << "Failed to get chunk\n"; while (active_ && !stream_->waitForChunk(100)) { LOG(DEBUG) << "Waiting for chunk\n"; if ((handle_ != nullptr) && (chronos::getTickCount() - lastChunkTick > 5000)) { LOG(NOTICE) << "No chunk received for 5000ms. Closing ALSA.\n"; uninitAlsa(); stream_->clearChunks(); } } } } } vector AlsaPlayer::pcm_list() { void **hints, **n; char *name, *descr, *io; vector result; PcmDevice pcmDevice; if (snd_device_name_hint(-1, "pcm", &hints) < 0) return result; n = hints; size_t idx(0); while (*n != nullptr) { name = snd_device_name_get_hint(*n, "NAME"); descr = snd_device_name_get_hint(*n, "DESC"); io = snd_device_name_get_hint(*n, "IOID"); if (io != nullptr && strcmp(io, "Output") != 0) goto __end; pcmDevice.name = name; if (descr == nullptr) { pcmDevice.description = ""; } else { pcmDevice.description = descr; } pcmDevice.idx = idx++; result.push_back(pcmDevice); __end: if (name != nullptr) free(name); if (descr != nullptr) free(descr); if (io != nullptr) free(io); n++; } snd_device_name_free_hint(hints); return result; } snapcast-0.18.1/client/player/alsa_player.hpp000066400000000000000000000026201361407301600211750ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef ALSA_PLAYER_H #define ALSA_PLAYER_H #include "player.hpp" #include /// Audio Player /** * Audio player implementation using Alsa */ class AlsaPlayer : public Player { public: AlsaPlayer(const PcmDevice& pcmDevice, std::shared_ptr stream); ~AlsaPlayer() override; /// Set audio volume in range [0..1] void start() override; void stop() override; /// List the system's audio output devices static std::vector pcm_list(void); protected: void worker() override; private: void initAlsa(); void uninitAlsa(); snd_pcm_t* handle_; snd_pcm_uframes_t frames_; char* buff_; }; #endif snapcast-0.18.1/client/player/coreaudio_player.cpp000066400000000000000000000163441361407301600222320ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "coreaudio_player.hpp" #include #define NUM_BUFFERS 2 // http://stackoverflow.com/questions/4863811/how-to-use-audioqueue-to-play-a-sound-for-mac-osx-in-c // https://gist.github.com/andormade/1360885 void callback(void* custom_data, AudioQueueRef queue, AudioQueueBufferRef buffer) { CoreAudioPlayer* player = static_cast(custom_data); player->playerCallback(queue, buffer); } CoreAudioPlayer::CoreAudioPlayer(const PcmDevice& pcmDevice, std::shared_ptr stream) : Player(pcmDevice, stream), ms_(100), pubStream_(stream) { } CoreAudioPlayer::~CoreAudioPlayer() { } /// TODO: experimental. No output device can be configured yet. std::vector CoreAudioPlayer::pcm_list(void) { UInt32 propsize; AudioObjectPropertyAddress theAddress = {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}; AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize); int nDevices = propsize / sizeof(AudioDeviceID); AudioDeviceID* devids = new AudioDeviceID[nDevices]; AudioObjectGetPropertyData(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize, devids); std::vector result; for (int i = 0; i < nDevices; ++i) { if (devids[i] == kAudioDeviceUnknown) continue; UInt32 propSize; AudioObjectPropertyAddress theAddress = {kAudioDevicePropertyStreamConfiguration, kAudioDevicePropertyScopeOutput, 0}; if (AudioObjectGetPropertyDataSize(devids[i], &theAddress, 0, NULL, &propSize)) continue; AudioBufferList* buflist = (AudioBufferList*)malloc(propSize); if (AudioObjectGetPropertyData(devids[i], &theAddress, 0, NULL, &propSize, buflist)) continue; int channels = 0; for (UInt32 i = 0; i < buflist->mNumberBuffers; ++i) channels += buflist->mBuffers[i].mNumberChannels; free(buflist); if (channels == 0) continue; UInt32 maxlen = 1024; char buf[1024]; theAddress = {kAudioDevicePropertyDeviceName, kAudioDevicePropertyScopeOutput, 0}; AudioObjectGetPropertyData(devids[i], &theAddress, 0, NULL, &maxlen, buf); LOG(DEBUG) << "device: " << i << ", name: " << buf << ", channels: " << channels << "\n"; result.push_back(PcmDevice(i, buf)); } delete[] devids; return result; } void CoreAudioPlayer::playerCallback(AudioQueueRef queue, AudioQueueBufferRef bufferRef) { /// Estimate the playout delay by checking the number of frames left in the buffer /// and add ms_ (= complete buffer size). Based on trying. AudioTimeStamp timestamp; AudioQueueGetCurrentTime(queue, timeLine_, ×tamp, NULL); size_t bufferedFrames = (frames_ - ((uint64_t)timestamp.mSampleTime % frames_)) % frames_; size_t bufferedMs = bufferedFrames * 1000 / pubStream_->getFormat().rate + (ms_ * (NUM_BUFFERS - 1)); /// 15ms DAC delay. Based on trying. bufferedMs += 15; // LOG(INFO) << "buffered: " << bufferedFrames << ", ms: " << bufferedMs << ", mSampleTime: " << timestamp.mSampleTime << "\n"; /// TODO: sometimes this bufferedMS or AudioTimeStamp wraps around 1s (i.e. we're 1s out of sync (behind)) and recovers later on chronos::usec delay(bufferedMs * 1000); char* buffer = (char*)bufferRef->mAudioData; if (!pubStream_->getPlayerChunk(buffer, delay, frames_)) { if (chronos::getTickCount() - lastChunkTick > 5000) { LOG(NOTICE) << "No chunk received for 5000ms. Closing Audio Queue.\n"; uninitAudioQueue(queue); return; } // LOG(INFO) << "Failed to get chunk. Playing silence.\n"; memset(buffer, 0, buff_size_); } else { lastChunkTick = chronos::getTickCount(); adjustVolume(buffer, frames_); } // OSStatus status = AudioQueueEnqueueBuffer(queue, bufferRef, 0, NULL); if (!active_) { uninitAudioQueue(queue); } } void CoreAudioPlayer::worker() { while (active_) { if (pubStream_->waitForChunk(100)) { try { initAudioQueue(); } catch (const std::exception& e) { LOG(ERROR) << "Exception in worker: " << e.what() << "\n"; chronos::sleep(100); } } chronos::sleep(100); } } void CoreAudioPlayer::initAudioQueue() { const SampleFormat& sampleFormat = pubStream_->getFormat(); AudioStreamBasicDescription format; format.mSampleRate = sampleFormat.rate; format.mFormatID = kAudioFormatLinearPCM; format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; // | kAudioFormatFlagIsPacked; format.mBitsPerChannel = sampleFormat.bits; format.mChannelsPerFrame = sampleFormat.channels; format.mBytesPerFrame = sampleFormat.frameSize; format.mFramesPerPacket = 1; format.mBytesPerPacket = format.mBytesPerFrame * format.mFramesPerPacket; format.mReserved = 0; AudioQueueRef queue; AudioQueueNewOutput(&format, callback, this, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &queue); AudioQueueCreateTimeline(queue, &timeLine_); // Apple recommends this as buffer size: // https://developer.apple.com/library/content/documentation/MusicAudio/Conceptual/CoreAudioOverview/CoreAudioEssentials/CoreAudioEssentials.html // static const int maxBufferSize = 0x10000; // limit maximum size to 64K // static const int minBufferSize = 0x4000; // limit minimum size to 16K // // For 100ms @ 48000:16:2 we have 19.2K // frames: 4800, ms: 100, buffer size: 19200 frames_ = (sampleFormat.rate * ms_) / 1000; ms_ = frames_ * 1000 / sampleFormat.rate; buff_size_ = frames_ * sampleFormat.frameSize; LOG(INFO) << "frames: " << frames_ << ", ms: " << ms_ << ", buffer size: " << buff_size_ << "\n"; AudioQueueBufferRef buffers[NUM_BUFFERS]; for (int i = 0; i < NUM_BUFFERS; i++) { AudioQueueAllocateBuffer(queue, buff_size_, &buffers[i]); buffers[i]->mAudioDataByteSize = buff_size_; callback(this, queue, buffers[i]); } LOG(ERROR) << "CoreAudioPlayer::worker\n"; AudioQueueCreateTimeline(queue, &timeLine_); AudioQueueStart(queue, NULL); CFRunLoopRun(); } void CoreAudioPlayer::uninitAudioQueue(AudioQueueRef queue) { AudioQueueStop(queue, false); AudioQueueDispose(queue, false); pubStream_->clearChunks(); CFRunLoopStop(CFRunLoopGetCurrent()); } snapcast-0.18.1/client/player/coreaudio_player.hpp000066400000000000000000000032061361407301600222300ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef CORE_AUDIO_PLAYER_H #define CORE_AUDIO_PLAYER_H #include #include #include #include "player.hpp" /// Audio Player /** * Audio player implementation using CoreAudio * * Warning: * * !! This player is experimental and might not be maintained !! * */ class CoreAudioPlayer : public Player { public: CoreAudioPlayer(const PcmDevice& pcmDevice, std::shared_ptr stream); virtual ~CoreAudioPlayer(); void playerCallback(AudioQueueRef queue, AudioQueueBufferRef bufferRef); static std::vector pcm_list(void); protected: virtual void worker(); void initAudioQueue(); void uninitAudioQueue(AudioQueueRef queue); AudioQueueTimelineRef timeLine_; size_t ms_; size_t frames_; size_t buff_size_; std::shared_ptr pubStream_; long lastChunkTick; }; #endif snapcast-0.18.1/client/player/opensl_player.cpp000066400000000000000000000334261361407301600215600ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include #include #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "opensl_player.hpp" using namespace std; static constexpr auto kPhaseInit = "Init"; static constexpr auto kPhaseStart = "Start"; static constexpr auto kPhaseStop = "Stop"; // http://stackoverflow.com/questions/35730050/android-with-nexus-6-how-to-avoid-decreased-opensl-audio-thread-priority-rela?rq=1 // source: https://github.com/hrydgard/native/blob/master/android/native-audio-so.cpp // https://android.googlesource.com/platform/development/+/c21a505/ndk/platforms/android-9/samples/native-audio/jni/native-audio-jni.c // This callback handler is called every time a buffer finishes playing. // The documentation available is very unclear about how to best manage buffers. // I've chosen to this approach: Instantly enqueue a buffer that was rendered to the last time, // and then render the next. Hopefully it's okay to spend time in this callback after having enqueued. static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* context) { OpenslPlayer* player = static_cast(context); player->playerCallback(bq); } OpenslPlayer::OpenslPlayer(const PcmDevice& pcmDevice, std::shared_ptr stream) : Player(pcmDevice, stream), engineObject(NULL), engineEngine(NULL), outputMixObject(NULL), bqPlayerObject(NULL), bqPlayerPlay(NULL), bqPlayerBufferQueue(NULL), bqPlayerVolume(NULL), curBuffer(0), ms_(50), buff_size(0), pubStream_(stream) { initOpensl(); } OpenslPlayer::~OpenslPlayer() { uninitOpensl(); } void OpenslPlayer::playerCallback(SLAndroidSimpleBufferQueueItf bq) { if (bq != bqPlayerBufferQueue) { LOG(ERROR) << "Wrong bq!\n"; return; } /* static long lastTick = 0; long now = chronos::getTickCount(); int diff = 0; if (lastTick != 0) { diff = now - lastTick; // LOG(ERROR) << "diff: " << diff << ", frames: " << player->frames_ / 44.1 << "\n"; // if (diff <= 50) // { // usleep(1000 * (50 - diff)); // diff = 50; // } } lastTick = chronos::getTickCount(); */ // size_t d = player->frames_ / 0.48d; // LOG(ERROR) << "Delay: " << d << "\n"; // SLAndroidSimpleBufferQueueState state; // (*bq)->GetState(bq, &state); // cout << "bqPlayerCallback count: " << state.count << ", idx: " << state.index << "\n"; // diff = 0; // chronos::usec delay((250 - diff) * 1000); // while (active_ && !stream_->waitForChunk(100)) // LOG(INFO) << "Waiting for chunk\n"; if (!active_) return; chronos::usec delay(ms_ * 1000); if (!pubStream_->getPlayerChunk(buffer[curBuffer], delay, frames_)) { // LOG(INFO) << "Failed to get chunk. Playing silence.\n"; memset(buffer[curBuffer], 0, buff_size); } else { adjustVolume(buffer[curBuffer], frames_); } while (active_) { SLresult result = (*bq)->Enqueue(bq, buffer[curBuffer], buff_size); if (result == SL_RESULT_BUFFER_INSUFFICIENT) chronos::sleep(1); else break; } curBuffer ^= 1; // Switch buffer } std::string OpenslPlayer::resultToString(SLresult result) const { switch (result) { case SL_RESULT_SUCCESS: return "SL_RESULT_SUCCESS"; case SL_RESULT_PRECONDITIONS_VIOLATED: return "SL_RESULT_PRECONDITIONS_VIOLATED"; case SL_RESULT_PARAMETER_INVALID: return "SL_RESULT_PARAMETER_INVALID"; case SL_RESULT_MEMORY_FAILURE: return "SL_RESULT_MEMORY_FAILURE"; case SL_RESULT_RESOURCE_ERROR: return "SL_RESULT_RESOURCE_ERROR"; case SL_RESULT_RESOURCE_LOST: return "SL_RESULT_RESOURCE_LOST"; case SL_RESULT_IO_ERROR: return "SL_RESULT_IO_ERROR"; case SL_RESULT_BUFFER_INSUFFICIENT: return "SL_RESULT_BUFFER_INSUFFICIENT"; case SL_RESULT_CONTENT_CORRUPTED: return "SL_RESULT_CONTENT_CORRUPTED"; case SL_RESULT_CONTENT_UNSUPPORTED: return "SL_RESULT_CONTENT_UNSUPPORTED"; case SL_RESULT_CONTENT_NOT_FOUND: return "SL_RESULT_CONTENT_NOT_FOUND"; case SL_RESULT_PERMISSION_DENIED: return "SL_RESULT_PERMISSION_DENIED"; case SL_RESULT_FEATURE_UNSUPPORTED: return "SL_RESULT_FEATURE_UNSUPPORTED"; case SL_RESULT_INTERNAL_ERROR: return "SL_RESULT_INTERNAL_ERROR"; case SL_RESULT_UNKNOWN_ERROR: return "SL_RESULT_UNKNOWN_ERROR"; case SL_RESULT_OPERATION_ABORTED: return "SL_RESULT_OPERATION_ABORTED"; case SL_RESULT_CONTROL_LOST: return "SL_RESULT_CONTROL_LOST"; default: return "UNKNOWN"; } } void OpenslPlayer::throwUnsuccess(const std::string& phase, const std::string& what, SLresult result) { if (SL_RESULT_SUCCESS == result) return; stringstream ss; ss << phase << " failed, operation: " << what << ", result: " << resultToString(result) << "(" << result << ")"; throw SnapException(ss.str()); } void OpenslPlayer::initOpensl() { if (active_) return; const SampleFormat& format = stream_->getFormat(); frames_ = format.rate / (1000 / ms_); // * format.channels; // 1920; // 48000 * 2 / 50 // => 50ms buff_size = frames_ * format.frameSize /* 2 -> sample size */; LOG(INFO) << "frames: " << frames_ << ", channels: " << format.channels << ", rate: " << format.rate << ", buff: " << buff_size << "\n"; SLresult result; // create engine SLEngineOption engineOption[] = {{(SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE}}; result = slCreateEngine(&engineObject, 1, engineOption, 0, NULL, NULL); throwUnsuccess(kPhaseInit, "slCreateEngine", result); result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); throwUnsuccess(kPhaseInit, "EngineObject::Realize", result); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); throwUnsuccess(kPhaseInit, "EngineObject::GetInterface", result); result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, 0, 0); throwUnsuccess(kPhaseInit, "EngineEngine::CreateOutputMix", result); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); throwUnsuccess(kPhaseInit, "OutputMixObject::Realize", result); SLuint32 samplesPerSec = SL_SAMPLINGRATE_48; switch (format.rate) { case 8000: samplesPerSec = SL_SAMPLINGRATE_8; break; case 11025: samplesPerSec = SL_SAMPLINGRATE_11_025; break; case 16000: samplesPerSec = SL_SAMPLINGRATE_16; break; case 22050: samplesPerSec = SL_SAMPLINGRATE_22_05; break; case 24000: samplesPerSec = SL_SAMPLINGRATE_24; break; case 32000: samplesPerSec = SL_SAMPLINGRATE_32; break; case 44100: samplesPerSec = SL_SAMPLINGRATE_44_1; break; case 48000: samplesPerSec = SL_SAMPLINGRATE_48; break; case 64000: samplesPerSec = SL_SAMPLINGRATE_64; break; case 88200: samplesPerSec = SL_SAMPLINGRATE_88_2; break; case 96000: samplesPerSec = SL_SAMPLINGRATE_96; break; case 192000: samplesPerSec = SL_SAMPLINGRATE_192; break; default: throw SnapException("Sample rate not supported"); } SLuint32 bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; SLuint32 containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; switch (format.bits) { case 8: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_8; containerSize = SL_PCMSAMPLEFORMAT_FIXED_8; break; case 16: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; break; case 24: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_24; containerSize = SL_PCMSAMPLEFORMAT_FIXED_32; break; case 32: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_32; containerSize = SL_PCMSAMPLEFORMAT_FIXED_32; break; default: throw SnapException("Unsupported sample format: " + cpt::to_string(format.bits)); } SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_pcm = { SL_DATAFORMAT_PCM, format.channels, samplesPerSec, bitsPerSample, containerSize, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN}; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; // create audio player const SLInterfaceID ids[3] = {SL_IID_ANDROIDCONFIGURATION, SL_IID_PLAY, SL_IID_BUFFERQUEUE}; //, SL_IID_VOLUME}; const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; //, SL_BOOLEAN_TRUE}; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 3, ids, req); throwUnsuccess(kPhaseInit, "Engine::CreateAudioPlayer", result); SLAndroidConfigurationItf playerConfig; result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_ANDROIDCONFIGURATION, &playerConfig); throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result); SLint32 streamType = SL_ANDROID_STREAM_MEDIA; //// SLint32 streamType = SL_ANDROID_STREAM_VOICE; result = (*playerConfig)->SetConfiguration(playerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32)); throwUnsuccess(kPhaseInit, "PlayerConfig::SetConfiguration", result); result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); throwUnsuccess(kPhaseInit, "PlayerObject::Realize", result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result); result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, this); throwUnsuccess(kPhaseInit, "PlayerBufferQueue::RegisterCallback", result); // result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume); // throwUnsuccess("PlayerObject::GetInterface", result); result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PAUSED); throwUnsuccess(kPhaseInit, "PlayerPlay::SetPlayState", result); // Render and enqueue a first buffer. (or should we just play the buffer empty?) curBuffer = 0; buffer[0] = new char[buff_size]; buffer[1] = new char[buff_size]; active_ = true; memset(buffer[curBuffer], 0, buff_size); result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer[curBuffer], sizeof(buffer[curBuffer])); throwUnsuccess(kPhaseInit, "PlayerBufferQueue::Enqueue", result); curBuffer ^= 1; } void OpenslPlayer::uninitOpensl() { // if (!active_) // return; LOG(INFO) << "uninitOpensl\n"; SLresult result; LOG(INFO) << "OpenSLWrap_Shutdown - stopping playback\n"; if (bqPlayerPlay != NULL) { result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED); if (SL_RESULT_SUCCESS != result) LOG(ERROR) << "SetPlayState failed\n"; } LOG(INFO) << "OpenSLWrap_Shutdown - deleting player object\n"; if (bqPlayerObject != NULL) { (*bqPlayerObject)->Destroy(bqPlayerObject); bqPlayerObject = NULL; bqPlayerPlay = NULL; bqPlayerBufferQueue = NULL; bqPlayerVolume = NULL; } LOG(INFO) << "OpenSLWrap_Shutdown - deleting mix object\n"; if (outputMixObject != NULL) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = NULL; } LOG(INFO) << "OpenSLWrap_Shutdown - deleting engine object\n"; if (engineObject != NULL) { (*engineObject)->Destroy(engineObject); engineObject = NULL; engineEngine = NULL; } delete[] buffer[0]; buffer[0] = NULL; delete[] buffer[1]; buffer[1] = NULL; LOG(INFO) << "OpenSLWrap_Shutdown - finished\n"; active_ = false; } void OpenslPlayer::start() { SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); throwUnsuccess(kPhaseStart, "PlayerPlay::SetPlayState", result); } void OpenslPlayer::stop() { SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED); (*bqPlayerBufferQueue)->Clear(bqPlayerBufferQueue); throwUnsuccess(kPhaseStop, "PlayerPlay::SetPlayState", result); } void OpenslPlayer::worker() { } snapcast-0.18.1/client/player/opensl_player.hpp000066400000000000000000000037601361407301600215630ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef OPEN_SL_PLAYER_H #define OPEN_SL_PLAYER_H #include #include #include #include "player.hpp" typedef int (*AndroidAudioCallback)(short* buffer, int num_samples); /// OpenSL Audio Player /** * Player implementation for OpenSL (e.g. Android) */ class OpenslPlayer : public Player { public: OpenslPlayer(const PcmDevice& pcmDevice, std::shared_ptr stream); virtual ~OpenslPlayer(); virtual void start(); virtual void stop(); void playerCallback(SLAndroidSimpleBufferQueueItf bq); protected: void initOpensl(); void uninitOpensl(); virtual void worker(); void throwUnsuccess(const std::string& phase, const std::string& what, SLresult result); std::string resultToString(SLresult result) const; // engine interfaces SLObjectItf engineObject; SLEngineItf engineEngine; SLObjectItf outputMixObject; // buffer queue player interfaces SLObjectItf bqPlayerObject; SLPlayItf bqPlayerPlay; SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue; SLVolumeItf bqPlayerVolume; // Double buffering. int curBuffer; char* buffer[2]; size_t ms_; size_t frames_; size_t buff_size; std::shared_ptr pubStream_; }; #endif snapcast-0.18.1/client/player/pcm_device.hpp000066400000000000000000000020741361407301600210020ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef PCM_DEVICE_H #define PCM_DEVICE_H #include struct PcmDevice { PcmDevice() : idx(-1), name("default"){}; PcmDevice(int idx, const std::string& name, const std::string& description = "") : idx(idx), name(name), description(description){}; int idx; std::string name; std::string description; }; #endif snapcast-0.18.1/client/player/player.cpp000066400000000000000000000054141361407301600201740ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include #include #include "common/aixlog.hpp" #include "player.hpp" using namespace std; Player::Player(const PcmDevice& pcmDevice, std::shared_ptr stream) : active_(false), stream_(stream), pcmDevice_(pcmDevice), volume_(1.0), muted_(false), volCorrection_(1.0) { } void Player::start() { active_ = true; playerThread_ = thread(&Player::worker, this); } Player::~Player() { stop(); } void Player::stop() { if (active_) { active_ = false; playerThread_.join(); } } void Player::adjustVolume(char* buffer, size_t frames) { double volume = volume_; if (muted_) volume = 0.; const SampleFormat& sampleFormat = stream_->getFormat(); if ((volume < 1.0) || (volCorrection_ != 1.)) { volume *= volCorrection_; if (sampleFormat.sampleSize == 1) adjustVolume(buffer, frames * sampleFormat.channels, volume); else if (sampleFormat.sampleSize == 2) adjustVolume(buffer, frames * sampleFormat.channels, volume); else if (sampleFormat.sampleSize == 4) adjustVolume(buffer, frames * sampleFormat.channels, volume); } } // https://cgit.freedesktop.org/pulseaudio/pulseaudio/tree/src/pulse/volume.c#n260 // http://www.robotplanet.dk/audio/audio_gui_design/ // https://lists.linuxaudio.org/pipermail/linux-audio-dev/2009-May/thread.html#22198 void Player::setVolume_poly(double volume, double exp) { volume_ = std::pow(volume, exp); LOG(DEBUG) << "setVolume poly: " << volume << " => " << volume_ << "\n"; } // http://stackoverflow.com/questions/1165026/what-algorithms-could-i-use-for-audio-volume-level void Player::setVolume_exp(double volume, double base) { // double base = M_E; // double base = 10.; volume_ = (pow(base, volume) - 1) / (base - 1); LOG(DEBUG) << "setVolume exp: " << volume << " => " << volume_ << "\n"; } void Player::setVolume(double volume) { setVolume_exp(volume, 10.); } void Player::setMute(bool mute) { muted_ = mute; } snapcast-0.18.1/client/player/player.hpp000066400000000000000000000036671361407301600202110ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef PLAYER_H #define PLAYER_H #include "common/aixlog.hpp" #include "common/endian.hpp" #include "pcm_device.hpp" #include "stream.hpp" #include #include #include #include /// Audio Player /** * Abstract audio player implementation */ class Player { public: Player(const PcmDevice& pcmDevice, std::shared_ptr stream); virtual ~Player(); /// Set audio volume in range [0..1] virtual void setVolume(double volume); virtual void setMute(bool mute); virtual void start(); virtual void stop(); protected: virtual void worker() = 0; void setVolume_poly(double volume, double exp); void setVolume_exp(double volume, double base); template void adjustVolume(char* buffer, size_t count, double volume) { T* bufferT = (T*)buffer; for (size_t n = 0; n < count; ++n) bufferT[n] = endian::swap(endian::swap(bufferT[n]) * volume); } void adjustVolume(char* buffer, size_t frames); std::atomic active_; std::shared_ptr stream_; std::thread playerThread_; PcmDevice pcmDevice_; double volume_; bool muted_; double volCorrection_; }; #endif snapcast-0.18.1/client/snapclient.1000066400000000000000000000033511361407301600171200ustar00rootroot00000000000000.\"groff -Tascii -man snapclient.1 .TH SNAPCLIENT 1 "January 2020" .SH NAME snapclient - Snapcast client .SH SYNOPSIS \fBsnapclient\fR [\fIOPTION\fR]... .SH DESCRIPTION Snapcast is a multi-room client-server audio player, where all clients are time synchronized with the server to play perfectly synced audio. It's not a standalone player, but an extension that turns your existing audio player into a Sonos-like multi-room solution. .br The server's audio input is a named pipe `/tmp/snapfifo`. All data that is fed into this file will be send to the connected clients. One of the most generic ways to use Snapcast is in conjunction with the music player daemon or Mopidy, which can be configured to use a named pipe as audio output. .SS Options .TP \fB--help\fR produce help message .TP \fB-v, --version\fR show version number .TP \fB-l, --list\fR list pcm devices .TP \fB-s, --soundcard arg (=default)\fR index or name of the soundcard .TP \fB-e, --mstderr\fR send metadata to stderr .TP \fB-h, --host arg\fR server hostname or ip address .TP \fB-p, --port arg (=1704)\fR server port .TP \fB-d, --daemon [=arg(=-3)]\fR daemonize, optional process priority [-20..19] .TP \fB--user arg\fR the user[:group] to run snapclient as when daemonized .TP \fB--latency arg (=0)\fR latency of the soundcard .TP \fB-i, --instance arg (=1)\fR instance id .TP \fB--hostID arg\fR unique host id .SH FILES .TP \fI/etc/default/snapclient\fR the daemon default configuration file .SH "COPYRIGHT" Copyright (C) 2014-2020 Johannes Pohl (snapcast@badaix.de). License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH "SEE ALSO" snapserver(1) snapcast-0.18.1/client/snapclient.cpp000066400000000000000000000240761361407301600175510ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include #include #include #include "browseZeroConf/browse_mdns.hpp" #include "common/popl.hpp" #include "controller.hpp" #ifdef HAS_ALSA #include "player/alsa_player.hpp" #endif #ifdef HAS_DAEMON #include "common/daemon.hpp" #endif #include "common/aixlog.hpp" #include "common/signal_handler.hpp" #include "common/str_compat.hpp" #include "common/utils.hpp" #include "metadata.hpp" using namespace std; using namespace popl; using namespace std::chrono_literals; PcmDevice getPcmDevice(const std::string& soundcard) { #ifdef HAS_ALSA vector pcmDevices = AlsaPlayer::pcm_list(); try { int soundcardIdx = cpt::stoi(soundcard); for (auto dev : pcmDevices) if (dev.idx == soundcardIdx) return dev; } catch (...) { } for (auto dev : pcmDevices) if (dev.name.find(soundcard) != string::npos) return dev; #else std::ignore = soundcard; #endif PcmDevice pcmDevice; return pcmDevice; } int main(int argc, char** argv) { #ifdef MACOS #pragma message "Warning: the macOS support is experimental and might not be maintained" #endif int exitcode = EXIT_SUCCESS; try { string meta_script(""); string soundcard("default"); string host(""); size_t port(1704); int latency(0); size_t instance(1); OptionParser op("Allowed options"); auto helpSwitch = op.add("", "help", "produce help message"); auto groffSwitch = op.add("", "groff", "produce groff message"); auto debugOption = op.add, Attribute::hidden>("", "debug", "enable debug logging", ""); auto versionSwitch = op.add("v", "version", "show version number"); #if defined(HAS_ALSA) auto listSwitch = op.add("l", "list", "list pcm devices"); /*auto soundcardValue =*/op.add>("s", "soundcard", "index or name of the soundcard", "default", &soundcard); #endif auto metaStderr = op.add("e", "mstderr", "send metadata to stderr"); // auto metaHook = op.add>("m", "mhook", "script to call on meta tags", "", &meta_script); /*auto hostValue =*/op.add>("h", "host", "server hostname or ip address", "", &host); /*auto portValue =*/op.add>("p", "port", "server port", 1704, &port); #ifdef HAS_DAEMON int processPriority(-3); auto daemonOption = op.add>("d", "daemon", "daemonize, optional process priority [-20..19]", -3, &processPriority); auto userValue = op.add>("", "user", "the user[:group] to run snapclient as when daemonized"); #endif /*auto latencyValue =*/op.add>("", "latency", "latency of the soundcard", 0, &latency); /*auto instanceValue =*/op.add>("i", "instance", "instance id", 1, &instance); auto hostIdValue = op.add>("", "hostID", "unique host id", ""); try { op.parse(argc, argv); } catch (const std::invalid_argument& e) { cerr << "Exception: " << e.what() << std::endl; cout << "\n" << op << "\n"; exit(EXIT_FAILURE); } if (versionSwitch->is_set()) { cout << "snapclient v" << VERSION << "\n" << "Copyright (C) 2014-2020 BadAix (snapcast@badaix.de).\n" << "License GPLv3+: GNU GPL version 3 or later .\n" << "This is free software: you are free to change and redistribute it.\n" << "There is NO WARRANTY, to the extent permitted by law.\n\n" << "Written by Johannes M. Pohl.\n\n"; exit(EXIT_SUCCESS); } #ifdef HAS_ALSA if (listSwitch->is_set()) { vector pcmDevices = AlsaPlayer::pcm_list(); for (auto dev : pcmDevices) { cout << dev.idx << ": " << dev.name << "\n" << dev.description << "\n\n"; } exit(EXIT_SUCCESS); } #endif if (helpSwitch->is_set()) { cout << op << "\n"; exit(EXIT_SUCCESS); } if (groffSwitch->is_set()) { GroffOptionPrinter option_printer(&op); cout << option_printer.print(); exit(EXIT_SUCCESS); } if (instance <= 0) std::invalid_argument("instance id must be >= 1"); // XXX: Only one metadata option must be set AixLog::Log::init("snapclient", AixLog::Severity::trace, AixLog::Type::special); if (debugOption->is_set()) { AixLog::Log::instance().add_logsink(AixLog::Severity::trace, AixLog::Type::all, "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)"); if (!debugOption->value().empty()) AixLog::Log::instance().add_logsink(AixLog::Severity::trace, AixLog::Type::all, debugOption->value(), "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)"); } else { AixLog::Log::instance().add_logsink(AixLog::Severity::info, AixLog::Type::all, "%Y-%m-%d %H-%M-%S [#severity]"); } #ifdef HAS_DAEMON std::unique_ptr daemon; if (daemonOption->is_set()) { string pidFile = "/var/run/snapclient/pid"; if (instance != 1) pidFile += "." + cpt::to_string(instance); string user = ""; string group = ""; if (userValue->is_set()) { if (userValue->value().empty()) std::invalid_argument("user must not be empty"); vector user_group = utils::string::split(userValue->value(), ':'); user = user_group[0]; if (user_group.size() > 1) group = user_group[1]; } daemon.reset(new Daemon(user, group, pidFile)); daemon->daemonize(); if (processPriority < -20) processPriority = -20; else if (processPriority > 19) processPriority = 19; if (processPriority != 0) setpriority(PRIO_PROCESS, 0, processPriority); SLOG(NOTICE) << "daemon started" << std::endl; } #endif PcmDevice pcmDevice = getPcmDevice(soundcard); #if defined(HAS_ALSA) if (pcmDevice.idx == -1) { cout << "soundcard \"" << soundcard << "\" not found\n"; // exit(EXIT_FAILURE); } #endif bool active = true; std::shared_ptr controller; auto signal_handler = install_signal_handler({SIGHUP, SIGTERM, SIGINT}, [&active, &controller](int signal, const std::string& strsignal) { SLOG(INFO) << "Received signal " << signal << ": " << strsignal << "\n"; active = false; if (controller) { LOG(INFO) << "Stopping controller\n"; controller->stop(); } }); if (host.empty()) { #if defined(HAS_AVAHI) || defined(HAS_BONJOUR) BrowseZeroConf browser; mDNSResult avahiResult; while (active) { signal_handler.wait_for(500ms); if (!active) break; try { if (browser.browse("_snapcast._tcp", avahiResult, 5000)) { host = avahiResult.ip; port = avahiResult.port; if (avahiResult.ip_version == IPVersion::IPv6) host += "%" + cpt::to_string(avahiResult.iface_idx); LOG(INFO) << "Found server " << host << ":" << port << "\n"; break; } } catch (const std::exception& e) { SLOG(ERROR) << "Exception: " << e.what() << std::endl; } } #endif } if (active) { // Setup metadata handling std::shared_ptr meta; meta.reset(new MetadataAdapter); if (metaStderr) meta.reset(new MetaStderrAdapter); controller = make_shared(hostIdValue->value(), instance, meta); LOG(INFO) << "Latency: " << latency << "\n"; controller->run(pcmDevice, host, port, latency); // signal_handler.wait(); // controller->stop(); } } catch (const std::exception& e) { SLOG(ERROR) << "Exception: " << e.what() << std::endl; exitcode = EXIT_FAILURE; } SLOG(NOTICE) << "daemon terminated." << endl; exit(exitcode); } snapcast-0.18.1/client/stream.cpp000066400000000000000000000362521361407301600167030ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "stream.hpp" #include "common/aixlog.hpp" #include "time_provider.hpp" #include #include #include using namespace std; // using namespace chronos; namespace cs = chronos; Stream::Stream(const SampleFormat& sampleFormat) : format_(sampleFormat), sleep_(0), median_(0), shortMedian_(0), lastUpdate_(0), playedFrames_(0), bufferMs_(cs::msec(500)) { buffer_.setSize(500); shortBuffer_.setSize(100); miniBuffer_.setSize(20); // cardBuffer_.setSize(50); /* 48000 x ------- = ----- 47999,2 x - 1 x = 1,000016667 / (1,000016667 - 1) */ setRealSampleRate(format_.rate); } void Stream::setRealSampleRate(double sampleRate) { if (sampleRate == format_.rate) correctAfterXFrames_ = 0; else correctAfterXFrames_ = round((format_.rate / sampleRate) / (format_.rate / sampleRate - 1.)); // LOG(DEBUG) << "Correct after X: " << correctAfterXFrames_ << " (Real rate: " << sampleRate << ", rate: " << format_.rate << ")\n"; } void Stream::setBufferLen(size_t bufferLenMs) { bufferMs_ = cs::msec(bufferLenMs); } void Stream::clearChunks() { while (chunks_.size() > 0) chunks_.pop(); resetBuffers(); } void Stream::addChunk(msg::PcmChunk* chunk) { while (chunks_.size() * chunk->duration().count() > 10000) chunks_.pop(); chunks_.push(shared_ptr(chunk)); // LOG(DEBUG) << "new chunk: " << chunk->duration().count() << ", Chunks: " << chunks_.size() << "\n"; } bool Stream::waitForChunk(size_t ms) const { return chunks_.wait_for(std::chrono::milliseconds(ms)); } cs::time_point_clk Stream::getSilentPlayerChunk(void* outputBuffer, unsigned long framesPerBuffer) { if (!chunk_) chunk_ = chunks_.pop(); cs::time_point_clk tp = chunk_->start(); memset(outputBuffer, 0, framesPerBuffer * format_.frameSize); return tp; } /* time_point_ms Stream::seekTo(const time_point_ms& to) { if (!chunk) chunk_ = chunks_.pop(); // time_point_ms tp = chunk_->timePoint(); while (to > chunk_->timePoint())// + std::chrono::milliseconds((long int)chunk_->getDuration()))// { chunk_ = chunks_.pop(); LOG(DEBUG) << "\nto: " << Chunk::getAge(to) << "\t chunk: " << Chunk::getAge(chunk_->timePoint()) << "\n"; LOG(DEBUG) << "diff: " << std::chrono::duration_cast((to - chunk_->timePoint())).count() << "\n"; } chunk_->seek(std::chrono::duration_cast(to - chunk_->timePoint()).count() * format_.msRate()); return chunk_->timePoint(); } */ /* time_point_clk Stream::seek(long ms) { if (!chunk) chunk_ = chunks_.pop(); if (ms <= 0) return chunk_->start(); // time_point_ms tp = chunk_->timePoint(); while (ms > chunk_->duration().count()) { chunk_ = chunks_.pop(); ms -= min(ms, (long)chunk_->durationLeft().count()); } chunk_->seek(ms * format_.msRate()); return chunk_->start(); } */ cs::time_point_clk Stream::getNextPlayerChunk(void* outputBuffer, const cs::usec& timeout, unsigned long framesPerBuffer) { if (!chunk_ && !chunks_.try_pop(chunk_, timeout)) throw 0; cs::time_point_clk tp = chunk_->start(); char* buffer = (char*)outputBuffer; unsigned long read = 0; while (read < framesPerBuffer) { read += chunk_->readFrames(buffer + read * format_.frameSize, framesPerBuffer - read); if (chunk_->isEndOfChunk() && !chunks_.try_pop(chunk_, timeout)) throw 0; } return tp; } cs::time_point_clk Stream::getNextPlayerChunk(void* outputBuffer, const cs::usec& timeout, unsigned long framesPerBuffer, long framesCorrection) { if (framesCorrection == 0) return getNextPlayerChunk(outputBuffer, timeout, framesPerBuffer); long toRead = framesPerBuffer + framesCorrection; char* buffer = (char*)malloc(toRead * format_.frameSize); cs::time_point_clk tp = getNextPlayerChunk(buffer, timeout, toRead); float factor = (float)toRead / framesPerBuffer; //(float)(framesPerBuffer*channels_); // if (abs(framesCorrection) > 1) // LOG(INFO) << "correction: " << framesCorrection << ", factor: " << factor << "\n"; float idx = 0; for (size_t n = 0; n < framesPerBuffer; ++n) { size_t index(floor(idx)); // = (int)(ceil(n*factor)); memcpy((char*)outputBuffer + n * format_.frameSize, buffer + index * format_.frameSize, format_.frameSize); idx += factor; } free(buffer); return tp; } /* 2020-01-12 20-25-26 [Info] Chunk: 7 7 11 15 179 120 2020-01-12 20-25-27 [Info] Chunk: 6 6 8 15 212 122 2020-01-12 20-25-28 [Info] Chunk: 6 6 7 12 245 123 2020-01-12 20-25-29 [Info] Chunk: 5 6 6 9 279 117 2020-01-12 20-25-30 [Info] Chunk: 4 5 6 8 312 117 2020-01-12 20-25-30 [Error] Controller::onException: read_some: End of file 2020-01-12 20-25-30 [Error] Exception in Controller::worker(): read_some: End of file 2020-01-12 20-25-31 [Error] Exception in Controller::worker(): connect: Connection refused 2020-01-12 20-25-31 [Error] Error in socket shutdown: Transport endpoint is not connected 2020-01-12 20-25-32 [Error] Exception in Controller::worker(): connect: Connection refused 2020-01-12 20-25-32 [Error] Error in socket shutdown: Transport endpoint is not connected ^C2020-01-12 20-25-32 [Info] Received signal 2: Interrupt 2020-01-12 20-25-32 [Info] Stopping controller 2020-01-12 20-25-32 [Error] Error in socket shutdown: Bad file descriptor 2020-01-12 20-25-32 [Error] Exception: Invalid argument 2020-01-12 20-25-32 [Notice] daemon terminated. ================================================================= ==22383==ERROR: LeakSanitizer: detected memory leaks Direct leak of 5756 byte(s) in 1 object(s) allocated from: #0 0x7f3d60635602 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x98602) #1 0x448fc2 in Stream::getNextPlayerChunk(void*, std::chrono::duration > const&, unsigned long, long) /home/johannes/Develop/snapcast/client/stream.cpp:163 SUMMARY: AddressSanitizer: 5756 byte(s) leaked in 1 allocation(s). */ void Stream::updateBuffers(int age) { buffer_.add(age); miniBuffer_.add(age); shortBuffer_.add(age); } void Stream::resetBuffers() { buffer_.clear(); miniBuffer_.clear(); shortBuffer_.clear(); } bool Stream::getPlayerChunk(void* outputBuffer, const cs::usec& outputBufferDacTime, unsigned long framesPerBuffer) { if (outputBufferDacTime > bufferMs_) { LOG(INFO) << "outputBufferDacTime > bufferMs: " << cs::duration(outputBufferDacTime) << " > " << cs::duration(bufferMs_) << "\n"; sleep_ = cs::usec(0); return false; } if (!chunk_ && !chunks_.try_pop(chunk_, outputBufferDacTime)) { // LOG(INFO) << "no chunks available\n"; sleep_ = cs::usec(0); return false; } playedFrames_ += framesPerBuffer; /// we have a chunk /// age = chunk age (server now - rec time: some positive value) - buffer (e.g. 1000ms) + time to DAC /// age = 0 => play now /// age < 0 => play in -age /// age > 0 => too old cs::usec age = std::chrono::duration_cast(TimeProvider::serverNow() - chunk_->start()) - bufferMs_ + outputBufferDacTime; // LOG(INFO) << "age: " << age.count() / 1000 << "\n"; if ((sleep_.count() == 0) && (cs::abs(age) > cs::msec(200))) { LOG(INFO) << "age > 200: " << cs::duration(age) << "\n"; sleep_ = age; } try { // LOG(DEBUG) << "framesPerBuffer: " << framesPerBuffer << "\tms: " << framesPerBuffer*2 / PLAYER_CHUNK_MS_SIZE << "\t" << PLAYER_CHUNK_SIZE << "\n"; cs::nsec bufferDuration = cs::nsec(cs::nsec::rep(framesPerBuffer / format_.nsRate())); // LOG(DEBUG) << "buffer duration: " << bufferDuration.count() << "\n"; cs::usec correction = cs::usec(0); if (sleep_.count() != 0) { resetBuffers(); if (sleep_ < -bufferDuration / 2) { LOG(INFO) << "sleep < -bufferDuration/2: " << cs::duration(sleep_) << " < " << -cs::duration(bufferDuration) / 2 << ", "; // We're early: not enough chunks_. play silence. Reference chunk_ is the oldest (front) one sleep_ = chrono::duration_cast(TimeProvider::serverNow() - getSilentPlayerChunk(outputBuffer, framesPerBuffer) - bufferMs_ + outputBufferDacTime); LOG(INFO) << "sleep: " << cs::duration(sleep_) << "\n"; if (sleep_ < -bufferDuration / 2) return true; } else if (sleep_ > bufferDuration / 2) { LOG(INFO) << "sleep > bufferDuration/2: " << cs::duration(sleep_) << " > " << cs::duration(bufferDuration) / 2 << "\n"; // We're late: discard oldest chunks while (sleep_ > chunk_->duration()) { LOG(INFO) << "sleep > chunkDuration: " << cs::duration(sleep_) << " > " << chunk_->duration().count() << ", chunks: " << chunks_.size() << ", out: " << cs::duration(outputBufferDacTime) << ", needed: " << cs::duration(bufferDuration) << "\n"; sleep_ = std::chrono::duration_cast(TimeProvider::serverNow() - chunk_->start() - bufferMs_ + outputBufferDacTime); if (!chunks_.try_pop(chunk_, outputBufferDacTime)) { LOG(INFO) << "no chunks available\n"; chunk_ = nullptr; sleep_ = cs::usec(0); return false; } } } // out of sync, can be corrected by playing faster/slower if (sleep_ < -cs::usec(100)) { sleep_ += cs::usec(100); correction = -cs::usec(100); } else if (sleep_ > cs::usec(100)) { sleep_ -= cs::usec(100); correction = cs::usec(100); } else { LOG(INFO) << "Sleep " << cs::duration(sleep_) << "\n"; correction = sleep_; sleep_ = cs::usec(0); } } // framesCorrection = number of frames to be read more or less to get in-sync long framesCorrection = correction.count() * format_.usRate(); // sample rate correction if ((correctAfterXFrames_ != 0) && (playedFrames_ >= (unsigned long)abs(correctAfterXFrames_))) { framesCorrection += (correctAfterXFrames_ > 0) ? 1 : -1; playedFrames_ -= abs(correctAfterXFrames_); } age = std::chrono::duration_cast(TimeProvider::serverNow() - getNextPlayerChunk(outputBuffer, outputBufferDacTime, framesPerBuffer, framesCorrection) - bufferMs_ + outputBufferDacTime); setRealSampleRate(format_.rate); if (sleep_.count() == 0) { if (buffer_.full()) { if (cs::usec(abs(median_)) > cs::msec(1)) { LOG(INFO) << "pBuffer->full() && (abs(median_) > 1): " << median_ << "\n"; sleep_ = cs::usec(median_); } // else if (cs::usec(median_) > cs::usec(300)) // { // setRealSampleRate(format_.rate - format_.rate / 1000); // } // else if (cs::usec(median_) < -cs::usec(300)) // { // setRealSampleRate(format_.rate + format_.rate / 1000); // } } else if (shortBuffer_.full()) { if (cs::usec(abs(shortMedian_)) > cs::msec(5)) { LOG(INFO) << "pShortBuffer->full() && (abs(shortMedian_) > 5): " << shortMedian_ << "\n"; sleep_ = cs::usec(shortMedian_); } // else // { // setRealSampleRate(format_.rate + -shortMedian_ / 100); // } } else if (miniBuffer_.full() && (cs::usec(abs(miniBuffer_.median())) > cs::msec(50))) { LOG(INFO) << "pMiniBuffer->full() && (abs(pMiniBuffer->mean()) > 50): " << miniBuffer_.median() << "\n"; sleep_ = cs::usec((cs::msec::rep)miniBuffer_.mean()); } } if (sleep_.count() != 0) { static int lastAge(0); int msAge = cs::duration(age); if (lastAge != msAge) { lastAge = msAge; LOG(INFO) << "Sleep " << cs::duration(sleep_) << ", age: " << msAge << ", bufferDuration: " << cs::duration(bufferDuration) << "\n"; } } else if (shortBuffer_.full()) { if (cs::usec(shortMedian_) > cs::usec(100)) setRealSampleRate(format_.rate * 0.9999); else if (cs::usec(shortMedian_) < -cs::usec(100)) setRealSampleRate(format_.rate * 1.0001); } updateBuffers(age.count()); // print sync stats time_t now = time(nullptr); if (now != lastUpdate_) { lastUpdate_ = now; median_ = buffer_.median(); shortMedian_ = shortBuffer_.median(); LOG(INFO) << "Chunk: " << age.count() / 100 << "\t" << miniBuffer_.median() / 100 << "\t" << shortMedian_ / 100 << "\t" << median_ / 100 << "\t" << buffer_.size() << "\t" << cs::duration(outputBufferDacTime) << "\n"; // LOG(INFO) << "Chunk: " << age.count()/1000 << "\t" << miniBuffer_.median()/1000 << "\t" << shortMedian_/1000 << "\t" << median_/1000 << "\t" << // buffer_.size() << "\t" << cs::duration(outputBufferDacTime) << "\n"; } return (abs(cs::duration(age)) < 500); } catch (int e) { sleep_ = cs::usec(0); return false; } } snapcast-0.18.1/client/stream.hpp000066400000000000000000000055241361407301600167060ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef STREAM_H #define STREAM_H #include "common/queue.h" #include "common/sample_format.hpp" #include "double_buffer.hpp" #include "message/message.hpp" #include "message/pcm_chunk.hpp" #include #include /// Time synchronized audio stream /** * Queue with PCM data. * Returns "online" server-time-synchronized PCM data */ class Stream { public: Stream(const SampleFormat& format); /// Adds PCM data to the queue void addChunk(msg::PcmChunk* chunk); void clearChunks(); /// Get PCM data, which will be played out in "outputBufferDacTime" time /// frame = (num_channels) * (1 sample in bytes) = (2 channels) * (2 bytes (16 bits) per sample) = 4 bytes (32 bits) bool getPlayerChunk(void* outputBuffer, const chronos::usec& outputBufferDacTime, unsigned long framesPerBuffer); /// "Server buffer": playout latency, e.g. 1000ms void setBufferLen(size_t bufferLenMs); const SampleFormat& getFormat() const { return format_; } bool waitForChunk(size_t ms) const; private: chronos::time_point_clk getNextPlayerChunk(void* outputBuffer, const chronos::usec& timeout, unsigned long framesPerBuffer); chronos::time_point_clk getNextPlayerChunk(void* outputBuffer, const chronos::usec& timeout, unsigned long framesPerBuffer, long framesCorrection); chronos::time_point_clk getSilentPlayerChunk(void* outputBuffer, unsigned long framesPerBuffer); chronos::time_point_clk seek(long ms); // time_point_ms seekTo(const time_point_ms& to); void updateBuffers(int age); void resetBuffers(); void setRealSampleRate(double sampleRate); SampleFormat format_; chronos::usec sleep_; Queue> chunks_; // DoubleBuffer cardBuffer; DoubleBuffer miniBuffer_; DoubleBuffer buffer_; DoubleBuffer shortBuffer_; std::shared_ptr chunk_; int median_; int shortMedian_; time_t lastUpdate_; unsigned long playedFrames_; long correctAfterXFrames_; chronos::msec bufferMs_; }; #endif snapcast-0.18.1/client/time_provider.cpp000066400000000000000000000036671361407301600202640ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "time_provider.hpp" #include "common/aixlog.hpp" TimeProvider::TimeProvider() : diffToServer_(0) { diffBuffer_.setSize(200); } void TimeProvider::setDiff(const tv& c2s, const tv& s2c) { // tv latency = c2s - s2c; // double diff = (latency.sec * 1000. + latency.usec / 1000.) / 2.; double diff = ((double)c2s.sec / 2. - (double)s2c.sec / 2.) * 1000. + ((double)c2s.usec / 2. - (double)s2c.usec / 2.) / 1000.; setDiffToServer(diff); } void TimeProvider::setDiffToServer(double ms) { static int32_t lastTimeSync = 0; timeval now; chronos::systemtimeofday(&now); /// clear diffBuffer if last update is older than a minute if (!diffBuffer_.empty() && (std::abs(now.tv_sec - lastTimeSync) > 60)) { LOG(INFO) << "Last time sync older than a minute. Clearing time buffer\n"; diffToServer_ = ms * 1000; diffBuffer_.clear(); } lastTimeSync = now.tv_sec; diffBuffer_.add(ms * 1000); diffToServer_ = diffBuffer_.median(3); // LOG(INFO) << "setDiffToServer: " << ms << ", diff: " << diffToServer_ / 1000.f << "\n"; } /* long TimeProvider::getPercentileDiffToServer(size_t percentile) { return diffBuffer.percentile(percentile); } */ snapcast-0.18.1/client/time_provider.hpp000066400000000000000000000050101361407301600202510ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef TIME_PROVIDER_H #define TIME_PROVIDER_H #include "common/time_defs.hpp" #include "double_buffer.hpp" #include "message/message.hpp" #include #include /// Provides local and server time /** * Stores time difference to the server * Returns server's local system time. * Clients are using the server time to play audio in sync, independent of the client's system time */ class TimeProvider { public: static TimeProvider& getInstance() { static TimeProvider instance; return instance; } void setDiffToServer(double ms); void setDiff(const tv& c2s, const tv& s2c); template inline T getDiffToServer() const { return std::chrono::duration_cast(chronos::usec(diffToServer_)); } /* chronos::usec::rep getDiffToServer(); chronos::usec::rep getPercentileDiffToServer(size_t percentile); long getDiffToServerMs(); */ template static T sinceEpoche(const chronos::time_point_clk& point) { return std::chrono::duration_cast(point.time_since_epoch()); } static chronos::time_point_clk toTimePoint(const tv& timeval) { return chronos::time_point_clk(chronos::usec(timeval.usec) + chronos::sec(timeval.sec)); } inline static chronos::time_point_clk now() { return chronos::clk::now(); } inline static chronos::time_point_clk serverNow() { return chronos::clk::now() + TimeProvider::getInstance().getDiffToServer(); } private: TimeProvider(); TimeProvider(TimeProvider const&); // Don't Implement void operator=(TimeProvider const&); // Don't implement DoubleBuffer diffBuffer_; std::atomic diffToServer_; }; #endif snapcast-0.18.1/cmake/000077500000000000000000000000001361407301600144765ustar00rootroot00000000000000snapcast-0.18.1/cmake/CheckAtomic.cmake000066400000000000000000000126051361407301600176560ustar00rootroot00000000000000# ============================================================================== # LLVM Release License # ============================================================================== # University of Illinois/NCSA # Open Source License # # Copyright (c) 2003-2018 University of Illinois at Urbana-Champaign. # All rights reserved. # # Developed by: # # LLVM Team # # University of Illinois at Urbana-Champaign # # http://llvm.org # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal with # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimers. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimers in the # documentation and/or other materials provided with the distribution. # # * Neither the names of the LLVM Team, University of Illinois at # Urbana-Champaign, nor the names of its contributors may be used to # endorse or promote products derived from this Software without specific # prior written permission. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE # SOFTWARE. INCLUDE(CheckCXXSourceCompiles) INCLUDE(CheckLibraryExists) # Sometimes linking against libatomic is required for atomic ops, if # the platform doesn't support lock-free atomics. function(check_working_cxx_atomics varname) set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++11") CHECK_CXX_SOURCE_COMPILES(" #include std::atomic x; int main() { return std::atomic_is_lock_free(&x); } " ${varname}) set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) endfunction(check_working_cxx_atomics) function(check_working_cxx_atomics64 varname) set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "-std=c++11 ${CMAKE_REQUIRED_FLAGS}") CHECK_CXX_SOURCE_COMPILES(" #include #include std::atomic x (0); int main() { uint64_t i = x.load(std::memory_order_relaxed); return std::atomic_is_lock_free(&x); } " ${varname}) set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) endfunction(check_working_cxx_atomics64) function(check_working_cxx_atomics_2args varname) set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -latomic") CHECK_CXX_SOURCE_COMPILES(" int main() { __atomic_load(nullptr, 0); return 0; } " ${varname}) set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) endfunction(check_working_cxx_atomics_2args) function(check_working_cxx_atomics64_2args varname) set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -latomic") CHECK_CXX_SOURCE_COMPILES(" int main() { __atomic_load_8(nullptr, 0); return 0; } " ${varname}) set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) endfunction(check_working_cxx_atomics64_2args) # First check if atomics work without the library. check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITHOUT_LIB) # If not, check if the library exists, and atomics work with it. if(NOT HAVE_CXX_ATOMICS_WITHOUT_LIB) check_library_exists(atomic __atomic_fetch_add_4 "" HAVE_LIBATOMIC) if( NOT HAVE_LIBATOMIC ) check_working_cxx_atomics_2args(HAVE_LIBATOMIC_2ARGS) endif() if( HAVE_LIBATOMIC OR HAVE_LIBATOMIC_2ARGS ) list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic") set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS} -latomic") check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITH_LIB) if (NOT HAVE_CXX_ATOMICS_WITH_LIB) message(FATAL_ERROR "Host compiler must support std::atomic!") endif() else() # Check for 64 bit atomic operations. if(MSVC) set(HAVE_CXX_ATOMICS64_WITHOUT_LIB True) else() check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITHOUT_LIB) endif() # If not, check if the library exists, and atomics work with it. if( NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB ) check_library_exists(atomic __atomic_load_8 "" HAVE_CXX_LIBATOMICS64) if( NOT HAVE_CXX_LIBATOMICS64 ) check_working_cxx_atomics64_2args(HAVE_CXX_LIBATOMICS64_2ARGS) endif() if( HAVE_CXX_LIBATOMICS64 OR HAVE_CXX_LIBATOMICS64_2ARGS ) list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic") set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS} -latomic") check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITH_LIB) if (NOT HAVE_CXX_ATOMICS64_WITH_LIB) message(FATAL_ERROR "Host compiler must support std::atomic!") endif() else() message(FATAL_ERROR "Host compiler appears to require libatomic, but cannot find it.") endif() endif() endif() endif() snapcast-0.18.1/cmake/CheckCXX11StringSupport.cmake000066400000000000000000000034471361407301600220360ustar00rootroot00000000000000# This file is part of snapcast # Copyright (C) 2014-2020 Johannes Pohl # 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 3 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 . #[=======================================================================[.rst: CheckCXX11StringSupport ---------------------- Check if the C++ compiler supports std::to_string, std::stoi, ... See also: https://stackoverflow.com/questions/17950814/how-to-use-stdstoul-and-stdstoull-in-android/18124627#18124627 .. command:: CHECK_CXX11_STRING_SUPPORT :: CHECK_CXX11_STRING_SUPPORT(resultVar) Checks support for std::to_string, std::stoul, std::stoi, std::stod. The result will be stored in the internal cache variable specified by ``resultVar``, with a boolean true value for success and boolean false for failure. #]=======================================================================] include(CheckCXXSourceCompiles) macro (CHECK_CXX11_STRING_SUPPORT _RESULT) set(CMAKE_REQUIRED_DEFINITIONS -std=c++0x) set(_CHECK_CXX11_STRING_SUPPORT_SOURCE_CODE " #include int main() { std::to_string(1); std::stoul(\"1\"); std::stoi(\"1\"); std::stod(\"1\"); return 0; } ") CHECK_CXX_SOURCE_COMPILES("${_CHECK_CXX11_STRING_SUPPORT_SOURCE_CODE}" ${_RESULT}) endmacro () snapcast-0.18.1/cmake/TargetArch.cmake000066400000000000000000000126551361407301600175350ustar00rootroot00000000000000# Based on the Qt 5 processor detection code, so should be very accurate # https://qt.gitorious.org/qt/qtbase/blobs/master/src/corelib/global/qprocessordetection.h # Currently handles arm (v5, v6, v7), x86 (32/64), ia64, and ppc (32/64) # Regarding POWER/PowerPC, just as is noted in the Qt source, # "There are many more known variants/revisions that we do not handle/detect." set(archdetect_c_code " #if defined(__arm__) || defined(__TARGET_ARCH_ARM) #if defined(__ARM_ARCH_7__) \\ || defined(__ARM_ARCH_7A__) \\ || defined(__ARM_ARCH_7R__) \\ || defined(__ARM_ARCH_7M__) \\ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM-0 >= 7) #error cmake_ARCH armv7 #elif defined(__ARM_ARCH_6__) \\ || defined(__ARM_ARCH_6J__) \\ || defined(__ARM_ARCH_6T2__) \\ || defined(__ARM_ARCH_6Z__) \\ || defined(__ARM_ARCH_6K__) \\ || defined(__ARM_ARCH_6ZK__) \\ || defined(__ARM_ARCH_6M__) \\ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM-0 >= 6) #error cmake_ARCH armv6 #elif defined(__ARM_ARCH_5TEJ__) \\ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM-0 >= 5) #error cmake_ARCH armv5 #else #error cmake_ARCH arm #endif #elif defined(__i386) || defined(__i386__) || defined(_M_IX86) #error cmake_ARCH i386 #elif defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64) #error cmake_ARCH x86_64 #elif defined(__ia64) || defined(__ia64__) || defined(_M_IA64) #error cmake_ARCH ia64 #elif defined(__ppc__) || defined(__ppc) || defined(__powerpc__) \\ || defined(_ARCH_COM) || defined(_ARCH_PWR) || defined(_ARCH_PPC) \\ || defined(_M_MPPC) || defined(_M_PPC) #if defined(__ppc64__) || defined(__powerpc64__) || defined(__64BIT__) #error cmake_ARCH ppc64 #else #error cmake_ARCH ppc #endif #endif #error cmake_ARCH unknown ") # Set ppc_support to TRUE before including this file or ppc and ppc64 # will be treated as invalid architectures since they are no longer supported by Apple function(target_architecture output_var) if(APPLE AND CMAKE_OSX_ARCHITECTURES) # On OS X we use CMAKE_OSX_ARCHITECTURES *if* it was set # First let's normalize the order of the values # Note that it's not possible to compile PowerPC applications if you are using # the OS X SDK version 10.6 or later - you'll need 10.4/10.5 for that, so we # disable it by default # See this page for more information: # http://stackoverflow.com/questions/5333490/how-can-we-restore-ppc-ppc64-as-well-as-full-10-4-10-5-sdk-support-to-xcode-4 # Architecture defaults to i386 or ppc on OS X 10.5 and earlier, depending on the CPU type detected at runtime. # On OS X 10.6+ the default is x86_64 if the CPU supports it, i386 otherwise. foreach(osx_arch ${CMAKE_OSX_ARCHITECTURES}) if("${osx_arch}" STREQUAL "ppc" AND ppc_support) set(osx_arch_ppc TRUE) elseif("${osx_arch}" STREQUAL "i386") set(osx_arch_i386 TRUE) elseif("${osx_arch}" STREQUAL "x86_64") set(osx_arch_x86_64 TRUE) elseif("${osx_arch}" STREQUAL "ppc64" AND ppc_support) set(osx_arch_ppc64 TRUE) else() message(FATAL_ERROR "Invalid OS X arch name: ${osx_arch}") endif() endforeach() # Now add all the architectures in our normalized order if(osx_arch_ppc) list(APPEND ARCH ppc) endif() if(osx_arch_i386) list(APPEND ARCH i386) endif() if(osx_arch_x86_64) list(APPEND ARCH x86_64) endif() if(osx_arch_ppc64) list(APPEND ARCH ppc64) endif() else() file(WRITE "${CMAKE_BINARY_DIR}/arch.c" "${archdetect_c_code}") enable_language(C) # Detect the architecture in a rather creative way... # This compiles a small C program which is a series of ifdefs that selects a # particular #error preprocessor directive whose message string contains the # target architecture. The program will always fail to compile (both because # file is not a valid C program, and obviously because of the presence of the # #error preprocessor directives... but by exploiting the preprocessor in this # way, we can detect the correct target architecture even when cross-compiling, # since the program itself never needs to be run (only the compiler/preprocessor) try_run( run_result_unused compile_result_unused "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/arch.c" COMPILE_OUTPUT_VARIABLE ARCH CMAKE_FLAGS CMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES} ) # Parse the architecture name from the compiler output string(REGEX MATCH "cmake_ARCH ([a-zA-Z0-9_]+)" ARCH "${ARCH}") # Get rid of the value marker leaving just the architecture name string(REPLACE "cmake_ARCH " "" ARCH "${ARCH}") # If we are compiling with an unknown architecture this variable should # already be set to "unknown" but in the case that it's empty (i.e. due # to a typo in the code), then set it to unknown if (NOT ARCH) set(ARCH unknown) endif() endif() set(${output_var} "${ARCH}" PARENT_SCOPE) endfunction()snapcast-0.18.1/cmake/modules/000077500000000000000000000000001361407301600161465ustar00rootroot00000000000000snapcast-0.18.1/cmake/modules/FindAsio.cmake000066400000000000000000000000001361407301600206320ustar00rootroot00000000000000snapcast-0.18.1/common/000077500000000000000000000000001361407301600147065ustar00rootroot00000000000000snapcast-0.18.1/common/CMakeLists.txt000066400000000000000000000000701361407301600174430ustar00rootroot00000000000000add_library(common STATIC daemon.cpp sample_format.cpp) snapcast-0.18.1/common/aixlog.hpp000066400000000000000000000724071361407301600167140ustar00rootroot00000000000000/*** __ __ _ _ __ __ ___ / _\ ( )( \/ )( ) / \ / __) / \ )( ) ( / (_/\( O )( (_ \ \_/\_/(__)(_/\_)\____/ \__/ \___/ version 1.2.5 https://github.com/badaix/aixlog This file is part of aixlog Copyright (C) 2017-2020 Johannes Pohl This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. ***/ /// inspired by "eater": /// https://stackoverflow.com/questions/2638654/redirect-c-stdclog-to-syslog-on-unix #ifndef AIX_LOG_HPP #define AIX_LOG_HPP #ifndef _WIN32 #define HAS_SYSLOG_ 1 #endif #ifdef __APPLE__ #ifdef __MAC_OS_X_VERSION_MAX_ALLOWED #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1012 #define HAS_APPLE_UNIFIED_LOG_ 1 #endif #endif #endif #include #include #include #include #include #include #include #include #include #include #include #ifdef __ANDROID__ #include #endif #ifdef _WIN32 #include // ERROR macro is defined in Windows header // To avoid conflict between these macro and declaration of ERROR / DEBUG in SEVERITY enum // We save macro and undef it #pragma push_macro("ERROR") #pragma push_macro("DEBUG") #undef ERROR #undef DEBUG #endif #ifdef HAS_APPLE_UNIFIED_LOG_ #include #endif #ifdef HAS_SYSLOG_ #include #endif #ifdef __ANDROID__ // fix for bug "Android NDK __func__ definition is inconsistent with glibc and C++99" // https://bugs.chromium.org/p/chromium/issues/detail?id=631489 #ifdef __GNUC__ #define AIXLOG_INTERNAL__FUNC __FUNCTION__ #else #define AIXLOG_INTERNAL__FUNC __func__ #endif #else #define AIXLOG_INTERNAL__FUNC __func__ #endif /// Internal helper macros (exposed, but shouldn't be used directly) #define AIXLOG_INTERNAL__LOG_SEVERITY(SEVERITY_) std::clog << static_cast(SEVERITY_) << TAG() #define AIXLOG_INTERNAL__LOG_SEVERITY_TAG(SEVERITY_, TAG_) std::clog << static_cast(SEVERITY_) << TAG(TAG_) #define AIXLOG_INTERNAL__ONE_COLOR(FG_) AixLog::Color::FG_ #define AIXLOG_INTERNAL__TWO_COLOR(FG_, BG_) AixLog::TextColor(AixLog::Color::FG_, AixLog::Color::BG_) // https://stackoverflow.com/questions/3046889/optional-parameters-with-c-macros #define AIXLOG_INTERNAL__VAR_PARM(PARAM1_, PARAM2_, FUNC_, ...) FUNC_ #define AIXLOG_INTERNAL__LOG_MACRO_CHOOSER(...) AIXLOG_INTERNAL__VAR_PARM(__VA_ARGS__, AIXLOG_INTERNAL__LOG_SEVERITY_TAG, AIXLOG_INTERNAL__LOG_SEVERITY, ) #define AIXLOG_INTERNAL__COLOR_MACRO_CHOOSER(...) AIXLOG_INTERNAL__VAR_PARM(__VA_ARGS__, AIXLOG_INTERNAL__TWO_COLOR, AIXLOG_INTERNAL__ONE_COLOR, ) /// External logger macros // usage: LOG(SEVERITY) or LOG(SEVERITY, TAG) // e.g.: LOG(NOTICE) or LOG(NOTICE, "my tag") #define LOG(...) AIXLOG_INTERNAL__LOG_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__) << TIMESTAMP << FUNC #define SLOG(...) AIXLOG_INTERNAL__LOG_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__) << TIMESTAMP << SPECIAL << FUNC // usage: COLOR(TEXT_COLOR, BACKGROUND_COLOR) or COLOR(TEXT_COLOR) // e.g.: COLOR(yellow, blue) or COLOR(red) #define COLOR(...) AIXLOG_INTERNAL__COLOR_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__) #define FUNC AixLog::Function(AIXLOG_INTERNAL__FUNC, __FILE__, __LINE__) #define TAG AixLog::Tag #define COND AixLog::Conditional #define SPECIAL AixLog::Type::special #define TIMESTAMP AixLog::Timestamp(std::chrono::system_clock::now()) /** * @brief * Severity of the log message */ enum SEVERITY { TRACE = 0, DEBUG = 1, INFO = 2, NOTICE = 3, WARNING = 4, ERROR = 5, FATAL = 6 }; namespace AixLog { /** * @brief * Severity of the log message * * Mandatory parameter for the LOG macro */ enum class Severity : std::int8_t { // Mapping table from AixLog to other loggers. Boost is just for information. // https://chromium.googlesource.com/chromium/mini_chromium/+/master/base/logging.cc // // Aixlog Boost Syslog Android macOS EventLog Syslog Desc // // trace trace DEBUG VERBOSE DEBUG INFORMATION // debug debug DEBUG DEBUG DEBUG INFORMATION debug-level message // info info INFO INFO INFO SUCCESS informational message // notice NOTICE INFO INFO SUCCESS normal, but significant, condition // warning warning WARNING WARN DEFAULT WARNING warning conditions // error error ERROR ERROR ERROR ERROR error conditions // fatal fatal CRIT FATAL FAULT ERROR critical conditions // ALERT action must be taken immediately // EMERG system is unusable trace = SEVERITY::TRACE, debug = SEVERITY::DEBUG, info = SEVERITY::INFO, notice = SEVERITY::NOTICE, warning = SEVERITY::WARNING, error = SEVERITY::ERROR, fatal = SEVERITY::FATAL }; /** * @brief * Type of the log message or Sink * * "normal" messages will be logged by "normal" or "all" Sinks * "special" ones by "special" or "all" Sinks */ enum class Type { normal, special, all }; /** * @brief * Color constants used for console colors */ enum class Color { none = 0, NONE = 0, black = 1, BLACK = 1, red = 2, RED = 2, green = 3, GREEN = 3, yellow = 4, YELLOW = 4, blue = 5, BLUE = 5, magenta = 6, MAGENTA = 6, cyan = 7, CYAN = 7, white = 8, WHITE = 8 }; /** * @brief * Encapsulation of foreground and background color */ struct TextColor { TextColor(Color foreground = Color::none, Color background = Color::none) : foreground(foreground), background(background) { } Color foreground; Color background; }; /** * @brief * For Conditional logging of a log line */ struct Conditional { Conditional() : Conditional(true) { } Conditional(bool value) : is_true_(value) { } void set(bool value) { is_true_ = value; } bool is_true() const { return is_true_; } private: bool is_true_; }; /** * @brief * Timestamp of a log line * * to_string will convert the time stamp into a string, using the strftime syntax */ struct Timestamp { using time_point_sys_clock = std::chrono::time_point; Timestamp(std::nullptr_t) : is_null_(true) { } Timestamp() : Timestamp(nullptr) { } Timestamp(const time_point_sys_clock& time_point) : time_point(time_point), is_null_(false) { } Timestamp(time_point_sys_clock&& time_point) : time_point(std::move(time_point)), is_null_(false) { } virtual ~Timestamp() = default; explicit operator bool() const { return !is_null_; } /// strftime format + proprietary "#ms" for milliseconds std::string to_string(const std::string& format = "%Y-%m-%d %H-%M-%S.#ms") const { std::time_t now_c = std::chrono::system_clock::to_time_t(time_point); struct ::tm now_tm = localtime_xp(now_c); char buffer[256]; strftime(buffer, sizeof buffer, format.c_str(), &now_tm); std::string result(buffer); size_t pos = result.find("#ms"); if (pos != std::string::npos) { int ms_part = std::chrono::time_point_cast(time_point).time_since_epoch().count() % 1000; char ms_str[4]; if (snprintf(ms_str, 4, "%03d", ms_part) >= 0) result.replace(pos, 3, ms_str); } return result; } time_point_sys_clock time_point; private: bool is_null_; inline std::tm localtime_xp(std::time_t timer) const { std::tm bt; #if defined(__unix__) localtime_r(&timer, &bt); #elif defined(_MSC_VER) localtime_s(&bt, &timer); #else static std::mutex mtx; std::lock_guard lock(mtx); bt = *std::localtime(&timer); #endif return bt; } }; /** * @brief * Tag (string) for log line */ struct Tag { Tag(std::nullptr_t) : text(""), is_null_(true) { } Tag() : Tag(nullptr) { } Tag(const std::string& text) : text(text), is_null_(false) { } Tag(std::string&& text) : text(std::move(text)), is_null_(false) { } virtual ~Tag() = default; explicit operator bool() const { return !is_null_; } std::string text; private: bool is_null_; }; /** * @brief * Capture function, file and line number of the log line */ struct Function { Function(const std::string& name, const std::string& file, size_t line) : name(name), file(file), line(line), is_null_(false) { } Function(std::string&& name, std::string&& file, size_t line) : name(std::move(name)), file(std::move(file)), line(line), is_null_(false) { } Function(std::nullptr_t) : name(""), file(""), line(0), is_null_(true) { } Function() : Function(nullptr) { } virtual ~Function() = default; explicit operator bool() const { return !is_null_; } std::string name; std::string file; size_t line; private: bool is_null_; }; /** * @brief * Collection of a log line's meta data */ struct Metadata { Metadata() : severity(Severity::trace), tag(nullptr), type(Type::normal), function(nullptr), timestamp(nullptr) { } Severity severity; Tag tag; Type type; Function function; Timestamp timestamp; }; /** * @brief * Abstract log sink * * All log sinks must inherit from this Sink */ struct Sink { Sink(Severity severity, Type type) : severity(severity), sink_type_(type) { } virtual ~Sink() = default; virtual void log(const Metadata& metadata, const std::string& message) = 0; virtual Type get_type() const { return sink_type_; } virtual Sink& set_type(Type sink_type) { sink_type_ = sink_type; return *this; } Severity severity; protected: Type sink_type_; }; /// ostream operators << for the meta data structs static std::ostream& operator<<(std::ostream& os, const Severity& log_severity); static std::ostream& operator<<(std::ostream& os, const Type& log_type); static std::ostream& operator<<(std::ostream& os, const Timestamp& timestamp); static std::ostream& operator<<(std::ostream& os, const Tag& tag); static std::ostream& operator<<(std::ostream& os, const Function& function); static std::ostream& operator<<(std::ostream& os, const Conditional& conditional); static std::ostream& operator<<(std::ostream& os, const Color& color); static std::ostream& operator<<(std::ostream& os, const TextColor& text_color); using log_sink_ptr = std::shared_ptr; /** * @brief * Main Logger class with "Log::init" * * Don't use it directly, but call once "Log::init" with your log sink instances. * The Log class will simply redirect clog to itself (as a streambuf) and * forward whatever went to clog to the log sink instances */ class Log : public std::basic_streambuf> { public: static Log& instance() { static Log instance_; return instance_; } /// Without "init" every LOG(X) will simply go to clog static void init(const std::vector log_sinks = {}) { Log::instance().log_sinks_.clear(); for (const auto& sink : log_sinks) Log::instance().add_logsink(sink); } template static std::shared_ptr init(Ts&&... params) { std::shared_ptr sink = Log::instance().add_logsink(std::forward(params)...); init({sink}); return sink; } template std::shared_ptr add_logsink(Ts&&... params) { std::lock_guard lock(mutex_); static_assert(std::is_base_of::type>::value, "type T must be a Sink"); std::shared_ptr sink = std::make_shared(std::forward(params)...); log_sinks_.push_back(sink); return sink; } void add_logsink(const log_sink_ptr& sink) { std::lock_guard lock(mutex_); log_sinks_.push_back(sink); } void remove_logsink(const log_sink_ptr& sink) { std::lock_guard lock(mutex_); log_sinks_.erase(std::remove(log_sinks_.begin(), log_sinks_.end(), sink), log_sinks_.end()); } static std::string to_string(Severity logSeverity) { switch (logSeverity) { case Severity::trace: return "Trace"; case Severity::debug: return "Debug"; case Severity::info: return "Info"; case Severity::notice: return "Notice"; case Severity::warning: return "Warn"; case Severity::error: return "Error"; case Severity::fatal: return "Fatal"; default: std::stringstream ss; ss << logSeverity; return ss.str(); } } protected: Log() noexcept { std::clog.rdbuf(this); std::clog << Severity() << Type::normal << Tag() << Function() << Conditional() << AixLog::Color::NONE << std::flush; } virtual ~Log() { sync(); } int sync() override { std::lock_guard lock(mutex_); if (!buffer_.str().empty()) { if (conditional_.is_true()) { for (const auto& sink : log_sinks_) { if ((metadata_.type == Type::all) || (sink->get_type() == Type::all) || (metadata_.type == sink->get_type())) if (metadata_.severity >= sink->severity) sink->log(metadata_, buffer_.str()); } } buffer_.str(""); buffer_.clear(); } return 0; } int overflow(int c) override { std::lock_guard lock(mutex_); if (c != EOF) { if (c == '\n') sync(); else buffer_ << static_cast(c); } else { sync(); } return c; } private: friend std::ostream& operator<<(std::ostream& os, const Severity& log_severity); friend std::ostream& operator<<(std::ostream& os, const Type& log_type); friend std::ostream& operator<<(std::ostream& os, const Timestamp& timestamp); friend std::ostream& operator<<(std::ostream& os, const Tag& tag); friend std::ostream& operator<<(std::ostream& os, const Function& function); friend std::ostream& operator<<(std::ostream& os, const Conditional& conditional); std::stringstream buffer_; Metadata metadata_; Conditional conditional_; std::vector log_sinks_; std::recursive_mutex mutex_; }; /** * @brief * Abstract log sink with support for formatting log message * * "format" in the c'tor defines a log pattern. * For every log message, these placeholders will be substituded: * - strftime syntax is used to format the logging time stamp (%Y, %m, %d, ...) * - #ms: milliseconds part of the logging time stamp with leading zeros * - #severity: log severity * - #tag_func: the log tag. If empty, the function * - #tag: the log tag * - #function: the function * - #message: the log message */ struct SinkFormat : public Sink { SinkFormat(Severity severity, Type type, const std::string& format) : Sink(severity, type), format_(format) { } virtual void set_format(const std::string& format) { format_ = format; } void log(const Metadata& metadata, const std::string& message) override = 0; protected: virtual void do_log(std::ostream& stream, const Metadata& metadata, const std::string& message) const { std::string result = format_; if (metadata.timestamp) result = metadata.timestamp.to_string(result); size_t pos = result.find("#severity"); if (pos != std::string::npos) result.replace(pos, 9, Log::to_string(metadata.severity)); pos = result.find("#tag_func"); if (pos != std::string::npos) result.replace(pos, 9, metadata.tag ? metadata.tag.text : (metadata.function ? metadata.function.name : "log")); pos = result.find("#tag"); if (pos != std::string::npos) result.replace(pos, 4, metadata.tag ? metadata.tag.text : ""); pos = result.find("#function"); if (pos != std::string::npos) result.replace(pos, 9, metadata.function ? metadata.function.name : ""); pos = result.find("#message"); if (pos != std::string::npos) { result.replace(pos, 8, message); stream << result << std::endl; } else { if (result.empty() || (result.back() == ' ')) stream << result << message << std::endl; else stream << result << " " << message << std::endl; } } std::string format_; }; /** * @brief * Formatted logging to cout */ struct SinkCout : public SinkFormat { SinkCout(Severity severity, Type type, const std::string& format = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)") : SinkFormat(severity, type, format) { } void log(const Metadata& metadata, const std::string& message) override { do_log(std::cout, metadata, message); } }; /** * @brief * Formatted logging to cerr */ struct SinkCerr : public SinkFormat { SinkCerr(Severity severity, Type type, const std::string& format = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)") : SinkFormat(severity, type, format) { } void log(const Metadata& metadata, const std::string& message) override { do_log(std::cerr, metadata, message); } }; /** * @brief * Formatted logging to file */ struct SinkFile : public SinkFormat { SinkFile(Severity severity, Type type, const std::string& filename, const std::string& format = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)") : SinkFormat(severity, type, format) { ofs.open(filename.c_str(), std::ofstream::out | std::ofstream::trunc); } ~SinkFile() override { ofs.close(); } void log(const Metadata& metadata, const std::string& message) override { do_log(ofs, metadata, message); } protected: mutable std::ofstream ofs; }; #ifdef _WIN32 /** * @brief * Windows: Logging to OutputDebugString * * Not tested due to unavailability of Windows */ struct SinkOutputDebugString : public Sink { SinkOutputDebugString(Severity severity, Type type = Type::all) : Sink(severity, type) { } void log(const Metadata& metadata, const std::string& message) override { OutputDebugString(message.c_str()); } }; #endif #ifdef HAS_APPLE_UNIFIED_LOG_ /** * @brief * macOS: Logging to Apples system logger */ struct SinkUnifiedLogging : public Sink { SinkUnifiedLogging(Severity severity, Type type = Type::all) : Sink(severity, type) { } os_log_type_t get_os_log_type(Severity severity) const { // https://developer.apple.com/documentation/os/os_log_type_t?language=objc switch (severity) { case Severity::trace: case Severity::debug: return OS_LOG_TYPE_DEBUG; case Severity::info: case Severity::notice: return OS_LOG_TYPE_INFO; case Severity::warning: return OS_LOG_TYPE_DEFAULT; case Severity::error: return OS_LOG_TYPE_ERROR; case Severity::fatal: return OS_LOG_TYPE_FAULT; default: return OS_LOG_TYPE_DEFAULT; } } void log(const Metadata& metadata, const std::string& message) override { os_log_with_type(OS_LOG_DEFAULT, get_os_log_type(metadata.severity), "%{public}s", message.c_str()); } }; #endif #ifdef HAS_SYSLOG_ /** * @brief * UNIX: Logging to syslog */ struct SinkSyslog : public Sink { SinkSyslog(const char* ident, Severity severity, Type type) : Sink(severity, type) { openlog(ident, LOG_PID, LOG_USER); } ~SinkSyslog() override { closelog(); } int get_syslog_priority(Severity severity) const { // http://unix.superglobalmegacorp.com/Net2/newsrc/sys/syslog.h.html switch (severity) { case Severity::trace: case Severity::debug: return LOG_DEBUG; case Severity::info: return LOG_INFO; case Severity::notice: return LOG_NOTICE; case Severity::warning: return LOG_WARNING; case Severity::error: return LOG_ERR; case Severity::fatal: return LOG_CRIT; default: return LOG_INFO; } } void log(const Metadata& metadata, const std::string& message) override { syslog(get_syslog_priority(metadata.severity), "%s", message.c_str()); } }; #endif #ifdef __ANDROID__ /** * @brief * Android: Logging to android log * * Use logcat to read the logs */ struct SinkAndroid : public Sink { SinkAndroid(const std::string& ident, Severity severity, Type type = Type::all) : Sink(severity, type), ident_(ident) { } android_LogPriority get_android_prio(Severity severity) const { // https://developer.android.com/ndk/reference/log_8h.html switch (severity) { case Severity::trace: return ANDROID_LOG_VERBOSE; case Severity::debug: return ANDROID_LOG_DEBUG; case Severity::info: case Severity::notice: return ANDROID_LOG_INFO; case Severity::warning: return ANDROID_LOG_WARN; case Severity::error: return ANDROID_LOG_ERROR; case Severity::fatal: return ANDROID_LOG_FATAL; default: return ANDROID_LOG_UNKNOWN; } } void log(const Metadata& metadata, const std::string& message) override { std::string tag = metadata.tag ? metadata.tag.text : (metadata.function ? metadata.function.name : ""); std::string log_tag; if (!ident_.empty() && !tag.empty()) log_tag = ident_ + "." + tag; else if (!ident_.empty()) log_tag = ident_; else if (!tag.empty()) log_tag = tag; else log_tag = "log"; __android_log_write(get_android_prio(metadata.severity), log_tag.c_str(), message.c_str()); } protected: std::string ident_; }; #endif #ifdef _WIN32 /** * @brief * Windows: Logging to event logger * * Not tested due to unavailability of Windows */ struct SinkEventLog : public Sink { SinkEventLog(const std::string& ident, Severity severity, Type type = Type::all) : Sink(severity, type) { event_log = RegisterEventSource(NULL, ident.c_str()); } WORD get_type(Severity severity) const { // https://msdn.microsoft.com/de-de/library/windows/desktop/aa363679(v=vs.85).aspx switch (severity) { case Severity::trace: case Severity::debug: return EVENTLOG_INFORMATION_TYPE; case Severity::info: case Severity::notice: return EVENTLOG_SUCCESS; case Severity::warning: return EVENTLOG_WARNING_TYPE; case Severity::error: case Severity::fatal: return EVENTLOG_ERROR_TYPE; default: return EVENTLOG_INFORMATION_TYPE; } } void log(const Metadata& metadata, const std::string& message) override { // We need this temp variable because we cannot take address of rValue const char* c_str = message.c_str(); ReportEvent(event_log, get_type(metadata.severity), 0, 0, NULL, 1, 0, &c_str, NULL); } protected: HANDLE event_log; }; #endif /** * @brief * Log to the system's native sys logger * * - Android: Android log * - macOS: unified log * - Windows: event log * - Unix: syslog */ struct SinkNative : public Sink { SinkNative(const std::string& ident, Severity severity, Type type = Type::all) : Sink(severity, type), log_sink_(nullptr), ident_(ident) { #ifdef __ANDROID__ log_sink_ = std::make_shared(ident_, severity, type); #elif HAS_APPLE_UNIFIED_LOG_ log_sink_ = std::make_shared(severity, type); #elif _WIN32 log_sink_ = std::make_shared(ident, severity, type); #elif HAS_SYSLOG_ log_sink_ = std::make_shared(ident_.c_str(), severity, type); #else /// will not throw or something. Use "get_logger()" to check for success log_sink_ = nullptr; #endif } virtual log_sink_ptr get_logger() { return log_sink_; } void log(const Metadata& metadata, const std::string& message) override { if (log_sink_ != nullptr) log_sink_->log(metadata, message); } protected: log_sink_ptr log_sink_; std::string ident_; }; /** * @brief * Forward log messages to a callback function * * Pass the callback function to the c'tor. * This can be any function that matches the signature of "callback_fun" * Might also be a lambda function */ struct SinkCallback : public Sink { using callback_fun = std::function; SinkCallback(Severity severity, Type type, callback_fun callback) : Sink(severity, type), callback_(callback) { } void log(const Metadata& metadata, const std::string& message) override { if (callback_) callback_(metadata, message); } private: callback_fun callback_; }; /** * @brief * ostream << operator for "Severity" * * Severity must be the first thing that is logged into clog, since it will reset the loggers metadata. */ static std::ostream& operator<<(std::ostream& os, const Severity& log_severity) { Log* log = dynamic_cast(os.rdbuf()); if (log != nullptr) { std::lock_guard lock(log->mutex_); if (log->metadata_.severity != log_severity) { log->sync(); log->metadata_.severity = log_severity; log->metadata_.type = Type::normal; log->metadata_.timestamp = nullptr; log->metadata_.tag = nullptr; log->metadata_.function = nullptr; log->conditional_.set(true); } } else { os << Log::to_string(log_severity); } return os; } static std::ostream& operator<<(std::ostream& os, const Type& log_type) { Log* log = dynamic_cast(os.rdbuf()); if (log != nullptr) { std::lock_guard lock(log->mutex_); log->metadata_.type = log_type; } return os; } static std::ostream& operator<<(std::ostream& os, const Timestamp& timestamp) { Log* log = dynamic_cast(os.rdbuf()); if (log != nullptr) { std::lock_guard lock(log->mutex_); log->metadata_.timestamp = timestamp; } else if (timestamp) { os << timestamp.to_string(); } return os; } static std::ostream& operator<<(std::ostream& os, const Tag& tag) { Log* log = dynamic_cast(os.rdbuf()); if (log != nullptr) { std::lock_guard lock(log->mutex_); log->metadata_.tag = tag; } else if (tag) { os << tag.text; } return os; } static std::ostream& operator<<(std::ostream& os, const Function& function) { Log* log = dynamic_cast(os.rdbuf()); if (log != nullptr) { std::lock_guard lock(log->mutex_); log->metadata_.function = function; } else if (function) { os << function.name; } return os; } static std::ostream& operator<<(std::ostream& os, const Conditional& conditional) { Log* log = dynamic_cast(os.rdbuf()); if (log != nullptr) { std::lock_guard lock(log->mutex_); log->conditional_.set(conditional.is_true()); } return os; } static std::ostream& operator<<(std::ostream& os, const TextColor& text_color) { os << "\033["; if ((text_color.foreground == Color::none) && (text_color.background == Color::none)) os << "0"; // reset colors if no params if (text_color.foreground != Color::none) { os << 29 + static_cast(text_color.foreground); if (text_color.background != Color::none) os << ";"; } if (text_color.background != Color::none) os << 39 + static_cast(text_color.background); os << "m"; return os; } static std::ostream& operator<<(std::ostream& os, const Color& color) { os << TextColor(color); return os; } } // namespace AixLog #ifdef _WIN32 // We restore the ERROR Windows macro #pragma pop_macro("ERROR") #pragma pop_macro("DEBUG") #endif #endif // AIX_LOG_HPP snapcast-0.18.1/common/daemon.cpp000066400000000000000000000115121361407301600166550ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #include "daemon.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "common/utils.hpp" #include "common/utils/file_utils.hpp" #include #include #include #include #include #include #include #include #include #include Daemon::Daemon(const std::string& user, const std::string& group, const std::string& pidfile) : pidFilehandle_(-1), user_(user), group_(group), pidfile_(pidfile) { if (pidfile.empty() || pidfile.find('/') == std::string::npos) throw SnapException("invalid pid file \"" + pidfile + "\""); } Daemon::~Daemon() { if (pidFilehandle_ != -1) close(pidFilehandle_); } void Daemon::daemonize() { std::string pidfileDir(pidfile_.substr(0, pidfile_.find_last_of('/'))); utils::file::mkdirRecursive(pidfileDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); /// Ensure only one copy pidFilehandle_ = open(pidfile_.c_str(), O_RDWR | O_CREAT, 0644); if (pidFilehandle_ == -1) { /// Couldn't open lock file throw SnapException("Could not open PID lock file \"" + pidfile_ + "\""); } uid_t user_uid = (uid_t)-1; gid_t user_gid = (gid_t)-1; std::string user_name; //#ifdef FREEBSD // bool had_group = false; //#endif if (!user_.empty()) { struct passwd* pwd = getpwnam(user_.c_str()); if (pwd == nullptr) throw SnapException("no such user \"" + user_ + "\""); user_uid = pwd->pw_uid; user_gid = pwd->pw_gid; user_name = strdup(user_.c_str()); /// this is needed by libs such as arts setenv("HOME", pwd->pw_dir, true); } if (!group_.empty()) { struct group* grp = getgrnam(group_.c_str()); if (grp == nullptr) throw SnapException("no such group \"" + group_ + "\""); user_gid = grp->gr_gid; //#ifdef FREEBSD // had_group = true; //#endif } if (chown(pidfile_.c_str(), user_uid, user_gid) == -1) { /// Couldn't open lock file throw SnapException("Could not chown PID lock file \"" + pidfile_ + "\""); } /// set gid if (user_gid != (gid_t)-1 && user_gid != getgid() && setgid(user_gid) == -1) throw SnapException("Failed to set group " + cpt::to_string((int)user_gid)); //#if defined(FREEBSD) && !defined(MACOS) //#ifdef FREEBSD /// init supplementary groups /// (must be done before we change our uid) /// no need to set the new user's supplementary groups if we are already this user // if (!had_group && user_uid != getuid() && initgroups(user_name, user_gid) == -1) // throw SnapException("Failed to set supplementary groups of user \"" + user + "\""); //#endif /// set uid if (user_uid != (uid_t)-1 && user_uid != getuid() && setuid(user_uid) == -1) throw SnapException("Failed to set user " + user_); /// Our process ID and Session ID pid_t pid, sid; /// Fork off the parent process pid = fork(); if (pid < 0) exit(EXIT_FAILURE); /// If we got a good PID, then we can exit the parent process. if (pid > 0) exit(EXIT_SUCCESS); /// Change the file mode mask umask(0); /// Open any logs here /// Create a new SID for the child process sid = setsid(); if (sid < 0) { /// Log the failure exit(EXIT_FAILURE); } /// Change the current working directory if ((chdir("/")) < 0) { /// Log the failure exit(EXIT_FAILURE); } /// Try to lock file if (lockf(pidFilehandle_, F_TLOCK, 0) == -1) throw SnapException("Could not lock PID lock file \"" + pidfile_ + "\""); char str[10]; /// Get and format PID sprintf(str, "%d\n", getpid()); /// write pid to lockfile if (write(pidFilehandle_, str, strlen(str)) != (int)strlen(str)) throw SnapException("Could not write PID to lock file \"" + pidfile_ + "\""); /// Close out the standard file descriptors close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } snapcast-0.18.1/common/daemon.hpp000066400000000000000000000020771361407301600166700ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl 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 3 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 . ***/ #ifndef DAEMON_H #define DAEMON_H #include class Daemon { public: Daemon(const std::string& user, const std::string& group, const std::string& pidfile); virtual ~Daemon(); void daemonize(); private: int pidFilehandle_; std::string user_; std::string group_; std::string pidfile_; }; #endif // DAEMON_H snapcast-0.18.1/common/endian.hpp000066400000000000000000000012361361407301600166570ustar00rootroot00000000000000#ifndef ENDIAN_HPP #define ENDIAN_HPP #include #ifdef IS_BIG_ENDIAN #define SWAP_16(x) (__builtin_bswap16(x)) #define SWAP_32(x) (__builtin_bswap32(x)) #define SWAP_64(x) (__builtin_bswap64(x)) #else #define SWAP_16(x) x #define SWAP_32(x) x #define SWAP_64(x) x #endif namespace endian { template T swap(const T&); template <> inline int8_t swap(const int8_t& val) { return val; } template <> inline int16_t swap(const int16_t& val) { return SWAP_16(val); } template <> inline int32_t swap(const int32_t& val) { return SWAP_32(val); } template <> inline int64_t swap(const int64_t& val) { return SWAP_64(val); } } #endif snapcast-0.18.1/common/json.hpp000066400000000000000000021776531361407301600164150ustar00rootroot00000000000000/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 3.1.2 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License . Copyright (c) 2013-2018 Niels Lohmann . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NLOHMANN_JSON_HPP #define NLOHMANN_JSON_HPP #define NLOHMANN_JSON_VERSION_MAJOR 3 #define NLOHMANN_JSON_VERSION_MINOR 1 #define NLOHMANN_JSON_VERSION_PATCH 2 #include // all_of, find, for_each #include // assert #include // and, not, or #include // nullptr_t, ptrdiff_t, size_t #include // hash, less #include // initializer_list #include // istream, ostream #include // iterator_traits, random_access_iterator_tag #include // accumulate #include // string, stoi, to_string #include // declval, forward, move, pair, swap // #include #ifndef NLOHMANN_JSON_FWD_HPP #define NLOHMANN_JSON_FWD_HPP #include // int64_t, uint64_t #include // map #include // allocator #include // string #include // vector #include "str_compat.hpp" /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template struct adl_serializer; template