pax_global_header 0000666 0000000 0000000 00000000064 13614073016 0014513 g ustar 00root root 0000000 0000000 52 comment=71f4b2f4ee6ca352e32e695d8ab1195aaef697f9
snapcast-0.18.1/ 0000775 0000000 0000000 00000000000 13614073016 0013416 5 ustar 00root root 0000000 0000000 snapcast-0.18.1/.clang-format 0000664 0000000 0000000 00000000754 13614073016 0015777 0 ustar 00root root 0000000 0000000 ---
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/.gitignore 0000664 0000000 0000000 00000001447 13614073016 0015414 0 ustar 00root root 0000000 0000000 # 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/.gitmodules 0000664 0000000 0000000 00000000547 13614073016 0015601 0 ustar 00root root 0000000 0000000 [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.yml 0000664 0000000 0000000 00000012405 13614073016 0015531 0 ustar 00root root 0000000 0000000 language: 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.txt 0000664 0000000 0000000 00000012471 13614073016 0016163 0 ustar 00root root 0000000 0000000 cmake_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/LICENSE 0000664 0000000 0000000 00000104506 13614073016 0014431 0 ustar 00root root 0000000 0000000 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/Makefile 0000664 0000000 0000000 00000001142 13614073016 0015054 0 ustar 00root root 0000000 0000000 .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.md 0000664 0000000 0000000 00000023254 13614073016 0014703 0 ustar 00root root 0000000 0000000 Snapcast
========

**S**y**n**chronous **a**udio **p**layer
[](https://travis-ci.org/badaix/snapcast)
[](https://github.com/badaix/snapcast/releases)
[](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)

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.md 0000664 0000000 0000000 00000001170 13614073016 0014504 0 ustar 00root root 0000000 0000000 TODO
====
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.md 0000664 0000000 0000000 00000034355 13614073016 0015701 0 ustar 00root root 0000000 0000000 # 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/ 0000775 0000000 0000000 00000000000 13614073016 0014674 5 ustar 00root root 0000000 0000000 snapcast-0.18.1/client/CMakeLists.txt 0000664 0000000 0000000 00000004761 13614073016 0017444 0 ustar 00root root 0000000 0000000 set(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/Makefile 0000664 0000000 0000000 00000015043 13614073016 0016337 0 ustar 00root root 0000000 0000000 # 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/ 0000775 0000000 0000000 00000000000 13614073016 0017643 5 ustar 00root root 0000000 0000000 snapcast-0.18.1/client/browseZeroConf/browse_avahi.cpp 0000664 0000000 0000000 00000017231 13614073016 0023024 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000004165 13614073016 0023033 0 ustar 00root root 0000000 0000000 /***
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.cpp 0000664 0000000 0000000 00000020245 13614073016 0023411 0 ustar 00root root 0000000 0000000 #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.hpp 0000664 0000000 0000000 00000000417 13614073016 0023415 0 ustar 00root root 0000000 0000000 #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.hpp 0000664 0000000 0000000 00000001103 13614073016 0022671 0 ustar 00root root 0000000 0000000 #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.sh 0000775 0000000 0000000 00000001673 13614073016 0020041 0 ustar 00root root 0000000 0000000 #/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.sh 0000775 0000000 0000000 00000000217 13614073016 0020662 0 ustar 00root root 0000000 0000000 #/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.cpp 0000664 0000000 0000000 00000015256 13614073016 0021106 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000010674 13614073016 0021112 0 ustar 00root root 0000000 0000000 /***
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.cpp 0000664 0000000 0000000 00000022344 13614073016 0017570 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000005702 13614073016 0017574 0 ustar 00root root 0000000 0000000 /***
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/ 0000775 0000000 0000000 00000000000 13614073016 0016301 5 ustar 00root root 0000000 0000000 snapcast-0.18.1/client/decoder/decoder.hpp 0000664 0000000 0000000 00000002237 13614073016 0020423 0 ustar 00root root 0000000 0000000 /***
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.cpp 0000664 0000000 0000000 00000020312 13614073016 0021375 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000002712 13614073016 0021406 0 ustar 00root root 0000000 0000000 /***
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.cpp 0000664 0000000 0000000 00000020734 13614073016 0021254 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000004111 13614073016 0021250 0 ustar 00root root 0000000 0000000 /***
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.cpp 0000664 0000000 0000000 00000007573 13614073016 0021474 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000002257 13614073016 0021473 0 ustar 00root root 0000000 0000000 /***
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.cpp 0000664 0000000 0000000 00000006735 13614073016 0021264 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000002016 13614073016 0021255 0 ustar 00root root 0000000 0000000 /***
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.hpp 0000664 0000000 0000000 00000006223 13614073016 0020213 0 ustar 00root root 0000000 0000000 /***
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/ 0000775 0000000 0000000 00000000000 13614073016 0015447 5 ustar 00root root 0000000 0000000 snapcast-0.18.1/client/etc/snapclient.plist 0000664 0000000 0000000 00000000703 13614073016 0020664 0 ustar 00root root 0000000 0000000
Label
de.badaix.snapcast.snapclient
ProgramArguments
/usr/local/bin/snapclient
RunAtLoad
KeepAlive