pax_global_header00006660000000000000000000000064146105111160014506gustar00rootroot0000000000000052 comment=000ea4f31eb7d91029052b3c261c7acc43273031 snapcast-0.28.0/000077500000000000000000000000001461051111600134115ustar00rootroot00000000000000snapcast-0.28.0/.clang-format000066400000000000000000000010171461051111600157630ustar00rootroot00000000000000--- AccessModifierOffset: '-4' AllowShortBlocksOnASingleLine: 'false' AllowShortCaseLabelsOnASingleLine: 'false' AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: 'false' AllowShortLoopsOnASingleLine: 'false' AlwaysBreakTemplateDeclarations: 'true' BreakBeforeBraces: Allman LambdaBodyIndentation: OuterScope ColumnLimit: '160' IndentCaseLabels: 'true' IndentWidth: '4' Language: Cpp MaxEmptyLinesToKeep: '3' PenaltyBreakComment: '100000' PointerAlignment: Left Standard: Latest UseTab: Never ... snapcast-0.28.0/.clang-tidy000066400000000000000000000071371461051111600154550ustar00rootroot00000000000000--- # Checks: '*,clang-diagnostic-*,clang-analyzer-*' Checks: '*,-llvmlibc-*,-readability-braces-around-statements,-hicpp-braces-around-statements,-google-readability-braces-around-statements,-hicpp-no-array-decay,-fuchsia-default-arguments-calls,-modernize-use-trailing-return-type,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-cppcoreguidelines-avoid-magic-numbers,-readability-magic-numbers,-bugprone-lambda-function-name,-hicpp-signed-bitwise,-cert-err60-cpp,-cppcoreguidelines-pro-type-reinterpret-cast,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-cppcoreguidelines-init-variables,-cppcoreguidelines-no-malloc,-hicpp-no-malloc,-google-readability-todo,-modernize-pass-by-value,-cppcoreguidelines-pro-type-member-init,-hicpp-member-init,-hicpp-avoid-c-arrays,-cppcoreguidelines-avoid-c-arrays,-modernize-avoid-c-arrays,-abseil-string-find-startswith,-google-build-using-namespace,-cppcoreguidelines-owning-memory,-readability-else-after-return,-cppcoreguidelines-pro-type-vararg,-hicpp-vararg,-readability-isolate-declaration,-cert-env33-c,-abseil-*' # Checks: '*,clang-diagnostic-*,clang-analyzer-*' # Checks: '*,-llvmlibc-restrict-system-libc-headers,-readability-braces-around-statements,-hicpp-braces-around-statements,-google-readability-braces-around-statements,-hicpp-no-array-decay,-fuchsia-default-arguments-calls,-modernize-use-trailing-return-type,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-cppcoreguidelines-avoid-magic-numbers,-readability-magic-numbers,-bugprone-lambda-function-name,-hicpp-signed-bitwise,-cert-err60-cpp,-cppcoreguidelines-pro-type-reinterpret-cast,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-cppcoreguidelines-init-variables,-cppcoreguidelines-no-malloc,-hicpp-no-malloc,-google-readability-todo,-modernize-pass-by-value,-cppcoreguidelines-pro-type-member-init,-hicpp-member-init,-hicpp-avoid-c-arrays,-cppcoreguidelines-avoid-c-arrays,-modernize-avoid-c-arrays,-abseil-string-find-startswith,-google-build-using-namespace,-cppcoreguidelines-owning-memory,-readability-else-after-return,-cppcoreguidelines-pro-type-vararg,-hicpp-vararg,-readability-isolate-declaration' WarningsAsErrors: '' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false FormatStyle: none User: johannes CheckOptions: - key: cert-dcl16-c.NewSuffixes value: 'L;LL;LU;LLU' - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField value: '0' - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors value: '1' - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic value: '1' - key: google-readability-braces-around-statements.ShortStatementLines value: '1' - key: google-readability-function-size.StatementThreshold value: '800' - key: google-readability-namespace-comments.ShortNamespaceLines value: '10' - key: google-readability-namespace-comments.SpacesBeforeComments value: '2' - key: modernize-loop-convert.MaxCopySize value: '16' - key: modernize-loop-convert.MinConfidence value: reasonable - key: modernize-loop-convert.NamingStyle value: CamelCase - key: modernize-pass-by-value.IncludeStyle value: llvm - key: modernize-replace-auto-ptr.IncludeStyle value: llvm - key: modernize-use-nullptr.NullMacros value: 'NULL' ... snapcast-0.28.0/.devcontainer/000077500000000000000000000000001461051111600161505ustar00rootroot00000000000000snapcast-0.28.0/.devcontainer/Dockerfile.alpine000066400000000000000000000012601461051111600214100ustar00rootroot00000000000000# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/cpp/.devcontainer/base.Dockerfile # [Choice] Debian / Ubuntu version (use Debian 11, Ubuntu 18.04/22.04 on local arm64/Apple Silicon): debian-11, debian-10, ubuntu-22.04, ubuntu-20.04, ubuntu-18.04 ARG VARIANT="alpine" FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} RUN echo "https://dl-cdn.alpinelinux.org/alpine/edge/testing/" >> /etc/apk/repositories RUN apk update && apk upgrade && apk add --no-cache bash librespot git alpine-sdk gdb libvorbis-dev soxr-dev flac-dev avahi-dev expat-dev boost-dev opus-dev alsa-lib-dev ninja ccache libstdc++ clang clang-dev snapcast-0.28.0/.devcontainer/Dockerfile.debian000066400000000000000000000007541461051111600213710ustar00rootroot00000000000000ARG VARIANT="debian-11" FROM mcr.microsoft.com/devcontainers/cpp:1-${VARIANT} # [Optional] Uncomment this section to install additional packages. RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ && apt-get -y install --no-install-recommends \ build-essential cmake \ libasound2-dev libpulse-dev libvorbisidec-dev libvorbis-dev libopus-dev libflac-dev \ libsoxr-dev alsa-utils libavahi-client-dev avahi-daemon libexpat1-dev libboost-dev \ cmake-format ccache snapcast-0.28.0/.devcontainer/Dockerfile.fedora000066400000000000000000000007571461051111600214120ustar00rootroot00000000000000ARG VARIANT="38" FROM fedora:${VARIANT} # [Optional] Uncomment this section to install additional packages. RUN dnf -y update \ && dnf -y install @development-tools cmake ccache \ && dnf -y install alsa-lib-devel avahi-devel gcc-c++ libatomic libvorbis-devel opus-devel \ pulseaudio-libs-devel flac-devel soxr-devel libstdc++-static expat-devel boost-devel \ && dnf clean all RUN useradd -rm -d /home/vscode -s /bin/bash -g root -u 1001 vscode USER vscode WORKDIR /home/vscode snapcast-0.28.0/.devcontainer/devcontainer.json000066400000000000000000000020161461051111600215230ustar00rootroot00000000000000// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: // https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/cpp { "name": "Snapcast-dev", "build": { "dockerfile": "Dockerfile.debian", // "args": { "VARIANT": "alpine" } }, "runArgs": ["--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined"], // Configure tool-specific properties. "customizations": { // Configure properties specific to VS Code. "vscode": { // Add the IDs of extensions you want installed when the container is created. "extensions": [ "ms-vscode.cpptools", "ms-vscode.cmake-tools" ] } }, // Use 'forwardPorts' to make a list of ports inside the container available locally. "forwardPorts": [1704, 1705, 1780], // Use 'postCreateCommand' to run commands after the container is created. // "postCreateCommand": "gcc -v", // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. "remoteUser": "vscode" } snapcast-0.28.0/.github/000077500000000000000000000000001461051111600147515ustar00rootroot00000000000000snapcast-0.28.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001461051111600171345ustar00rootroot00000000000000snapcast-0.28.0/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000010471461051111600216300ustar00rootroot00000000000000--- name: Bug report about: 'Report a bug' title: '' labels: assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Steps to Reproduce** 1. 2. 3. **Environment details** - OS: [e.g. Raspbian, debian, Windows] - Snapcast version [e.g. 0.21.0] - Installed from a package, self compiled, ... **Attach logfile if applicable** Generate logs with `snapclient --logfilter debug` or `snapserver --logging.filter debug` if possible and paste them in the following codeblock ```log # Replace this with your logs ``` snapcast-0.28.0/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000002741461051111600211270ustar00rootroot00000000000000blank_issues_enabled: true contact_links: - name: Ask a question url: https://github.com/badaix/snapcast/discussions about: Ask questions and discuss with other community memberssnapcast-0.28.0/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000011531461051111600226610ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea or enhancement for snapcast title: '' labels: feature request assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. snapcast-0.28.0/.github/pull_request_template.md000066400000000000000000000037471461051111600217250ustar00rootroot00000000000000[Describe your pull request here. Please read the text below the line, and make sure you follow the checklist.] * * * ## Pull Request Checklist * Contributions must be licensed under the [GPL-3.0 License](LICENSE) * This project loosely follows the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) * For better compatibility with embedded toolchains, the used C++ standard should be limited to C++17 * Code should be formatted by running `make reformat` * Branch from the `develop` branch and ensure it is up to date with the current `develop` branch before submitting your pull request. If it doesn't merge cleanly with `develop`, you may be asked to resolve the conflicts. Pull requests to master will be closed. * Commits should be as small as possible while ensuring that each commit is correct independently (i.e., each commit should compile and pass tests). * Pull requests must not contain compiled sources (already set by the default .gitignore) or binary files * Test your changes as thoroughly as possible before you commit them. Preferably, automate your test by unit/integration tests. If tested manually, provide information about the test scope in the PR description (e.g. “Test passed: Upgrade version from 0.42 to 0.42.23.”). * Create _Work In Progress [WIP]_ pull requests only if you need clarification or an explicit review before you can continue your work item. * If your patch is not getting reviewed or you need a specific person to review it, you can @-reply a reviewer asking for a review in the pull request or a comment, or you can ask for a review by contacting us via [email](mailto:snapcast@badaix.de). * Post review: * If a review requires you to change your commit(s), please test the changes again. * Amend the affected commit(s) and force push onto your branch. * Set respective comments in your GitHub review to resolved. * Create a general PR comment to notify the reviewers that your amendments are ready for another round of review. snapcast-0.28.0/.github/workflows/000077500000000000000000000000001461051111600170065ustar00rootroot00000000000000snapcast-0.28.0/.github/workflows/ci.yml000066400000000000000000000202561461051111600201310ustar00rootroot00000000000000name: CI on: push: pull_request: env: BOOST_VERSION: 1_84_0 jobs: static-analysis: strategy: fail-fast: false matrix: tool: - cppcheck runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - name: print environment run: env - name: dependencies run: sudo apt-get update && sudo apt-get install -yq libasound2-dev libsoxr-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libpulse-dev libavahi-client-dev avahi-daemon debhelper ccache expat cppcheck - name: cache boost id: cache-boost uses: actions/cache@v4 with: path: boost_${{ env.BOOST_VERSION }} key: boost-${{ env.BOOST_VERSION }} enableCrossOsArchive: true - name: get boost if: steps.cache-boost.outputs.cache-hit != 'true' run: | wget https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION//_/.}/source/boost_${BOOST_VERSION}.tar.bz2 tar xjf boost_${BOOST_VERSION}.tar.bz2 - name: configure run: | cmake -S . -B build \ -DWERROR=ON -DBUILD_TESTS=ON \ -DBOOST_ROOT=boost_${BOOST_VERSION} \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_EXPORT_COMPILE_COMMANDS=TRUE \ -DCMAKE_CXX_FLAGS="-DCMAKE_CXX_FLAGS=-DJSON_HAS_CPP_14" - name: analysis run: cmake --build build --target ${{ matrix.tool }} linux: strategy: fail-fast: false matrix: compiler: - clang-10 - clang-11 - clang-12 - clang-13 - clang-14 - clang-15 - gcc-9 - gcc-10 - gcc-11 - gcc-12 - gcc-13 include: - compiler: clang-10 cc: clang-10 cxx: clang++-10 os: ubuntu-20.04 - compiler: clang-11 cc: clang-11 cxx: clang++-11 os: ubuntu-20.04 - compiler: clang-12 cc: clang-12 cxx: clang++-12 os: ubuntu-20.04 - compiler: clang-13 cc: clang-13 cxx: clang++-13 os: ubuntu-22.04 - compiler: clang-14 cc: clang-14 cxx: clang++-14 os: ubuntu-22.04 - compiler: clang-15 cc: clang-15 cxx: clang++-15 os: ubuntu-22.04 - compiler: gcc-9 cc: gcc-9 cxx: g++-9 os: ubuntu-22.04 - compiler: gcc-10 cc: gcc-10 cxx: g++-10 os: ubuntu-22.04 - compiler: gcc-11 cc: gcc-11 cxx: g++-11 os: ubuntu-22.04 - compiler: gcc-12 cc: gcc-12 cxx: g++-12 os: ubuntu-22.04 - compiler: gcc-13 cc: gcc-13 cxx: g++-13 os: ubuntu-22.04 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - name: print environment run: env - name: dependencies run: sudo apt-get update && sudo apt-get install -yq libasound2-dev libsoxr-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libpulse-dev libavahi-client-dev avahi-daemon debhelper ccache expat cppcheck - name: cache boost id: cache-boost uses: actions/cache@v4 with: path: boost_${{ env.BOOST_VERSION }} key: boost-${{ env.BOOST_VERSION }} enableCrossOsArchive: true - name: get boost if: steps.cache-boost.outputs.cache-hit != 'true' run: | wget https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION//_/.}/source/boost_${BOOST_VERSION}.tar.bz2 tar xjf boost_${BOOST_VERSION}.tar.bz2 - name: cache ccache id: cache-ccache uses: actions/cache@v4 with: # TODO: use environment variable $HOME/.ccache path: /home/runner/.ccache key: ${{ runner.os }}-${{ matrix.compiler }}-ccache-${{ github.sha }} restore-keys: ${{ runner.os }}-${{ matrix.compiler }}-ccache- #- name: ccache dump config # run: ccache -p - name: configure run: | cmake -S . -B build \ -DWERROR=ON -DBUILD_TESTS=ON \ -DBOOST_ROOT=boost_${BOOST_VERSION} \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ -DCMAKE_EXPORT_COMPILE_COMMANDS=TRUE \ -DCMAKE_CXX_FLAGS="-DCMAKE_CXX_FLAGS=-DJSON_HAS_CPP_14" env: CC: ${{ matrix.cc }} CXX: ${{ matrix.cxx }} - name: build env: # TODO: use environment variable $HOME/.ccache CCACHE_DIR: /home/runner/.ccache run: cmake --build build --parallel 3 --verbose macos: strategy: fail-fast: false matrix: xcode: - "11.7" - "12.5.1" - "13.2.1" - "13.3.1" - "13.4.1" - "14.0.1" - "14.1" - "14.2" - "14.3" - "15.0" include: - xcode: "11.7" os: macos-11 - xcode: "12.5.1" os: macos-11 - xcode: "13.2.1" os: macos-11 - xcode: "13.3.1" os: macos-12 - xcode: "13.4.1" os: macos-12 - xcode: "14.0.1" os: macos-12 - xcode: "14.1" os: macos-12 - xcode: "14.2" os: macos-12 - xcode: "14.3" os: macos-13 - xcode: "15.0" os: macos-13 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - name: print environment run: env - name: dependencies run: brew install pkgconfig libsoxr ccache expat - name: cache boost id: cache-boost uses: actions/cache@v4 with: path: boost_${{ env.BOOST_VERSION }} key: boost-${{ env.BOOST_VERSION }} enableCrossOsArchive: true - name: get boost if: steps.cache-boost.outputs.cache-hit != 'true' run: | wget https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION//_/.}/source/boost_${BOOST_VERSION}.tar.bz2 tar xjf boost_${BOOST_VERSION}.tar.bz2 - name: cache ccache id: cache-ccache uses: actions/cache@v4 with: path: /Users/runner/Library/Caches/ccache key: ${{ runner.os }}-${{ matrix.xcode }}-ccache-${{ github.sha }} restore-keys: ${{ runner.os }}-${{ matrix.xcode }}-ccache- - name: configure run: | cmake -S . -B build \ -DWERROR=ON -DBUILD_TESTS=ON \ -DBOOST_ROOT=boost_${BOOST_VERSION} \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ -DCMAKE_CXX_FLAGS="-I/usr/local/include -DCMAKE_CXX_FLAGS=-DJSON_HAS_CPP_14" env: DEVELOPER_DIR: /Applications/Xcode_${{ matrix.xcode }}.app/Contents/Developer - name: build run: cmake --build build --parallel 3 --verbose windows: strategy: fail-fast: false matrix: compiler: - vs-16 - vs-17 include: - compiler: vs-16 os: windows-2019 vs: "Visual Studio 16 2019" - compiler: vs-17 os: windows-2022 vs: "Visual Studio 17 2022" runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - name: cache dependencies id: cache-dependencies uses: actions/cache@v4 with: #path: ${VCPKG_INSTALLATION_ROOT}\installed path: c:\vcpkg\installed key: ${{ runner.os }}-dependencies - name: dependencies if: steps.cache-dependencies.outputs.cache-hit != 'true' run: vcpkg.exe install libflac libvorbis soxr opus boost-asio --triplet x64-windows - name: configure run: | echo vcpkg installation root: ${env:VCPKG_INSTALLATION_ROOT} cmake -S . -B build -G "${{ matrix.vs }}" ` -DWERROR=ON -DBUILD_TESTS=ON ` -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" ` -DVCPKG_TARGET_TRIPLET="x64-windows" ` -DCMAKE_BUILD_TYPE=Release ` -DREVISION="${{ github.sha }}" - name: build run: cmake --build build --config Release --parallel 3 --verbose snapcast-0.28.0/.github/workflows/package.yml000066400000000000000000000225641461051111600211350ustar00rootroot00000000000000name: Package run-name: Package ${{ github.sha }} by @${{ github.actor }} on: workflow_dispatch: env: BOOST_VERSION: 1_84_0 SNAPWEB_VERSION: v0.7.0 jobs: deb: strategy: fail-fast: false matrix: debian: - bullseye - bookworm arch: - amd64 - armhf - arm64 include: - arch: "amd64" os: ubuntu-latest image_prefix: "debian:" - arch: "armhf" os: self-hosted-rpi4 image_prefix: "badaix/raspios-lite:" - arch: "arm64" os: self-hosted-rpi5 image_prefix: "badaix/raspios-lite:" runs-on: ${{ matrix.os }} name: deb (${{ matrix.arch }}, ${{ matrix.debian }}) timeout-minutes: 240 container: image: ${{matrix.image_prefix}}${{matrix.debian}} steps: - name: Get dependencies run: apt-get update && apt-get install -yq wget debhelper build-essential cmake git rename libatomic1 libasound2-dev libsoxr-dev libvorbisidec-dev libvorbis-dev libflac-dev libopus-dev alsa-utils libpulse-dev libavahi-client-dev avahi-daemon libexpat1-dev python3 ccache unzip env: DEBIAN_FRONTEND: noninteractive - name: Checkout uses: actions/checkout@v4 - name: Setup environment run: | echo "PARENT_DIR=$(dirname $GITHUB_WORKSPACE)" >> $GITHUB_ENV BOOST_DOT_VERSION=$(echo ${BOOST_VERSION} | sed 's/_/./g') echo "BOOST_DOT_VERSION=$BOOST_DOT_VERSION" >> $GITHUB_ENV echo "BOOST=boost_${BOOST_VERSION}" >> $GITHUB_ENV ln -s extras/package/debian debian - name: Create changelog run: | $GITHUB_WORKSPACE/debian/changelog_md2deb.py $GITHUB_WORKSPACE/changelog.md > $GITHUB_WORKSPACE/debian/changelog cat $GITHUB_WORKSPACE/debian/changelog - name: Clean up run: rm -rf ${{env.PARENT_DIR}}/snap*_${{ matrix.arch }}.deb - name: Cache boost id: cache-boost uses: actions/cache@v4 with: path: ${{env.BOOST}} key: ${{env.BOOST}} - name: Get boost if: steps.cache-boost.outputs.cache-hit != 'true' run: | wget https://boostorg.jfrog.io/artifactory/main/release/${{env.BOOST_DOT_VERSION}}/source/${{env.BOOST}}.tar.bz2 tar xjf ${{env.BOOST}}.tar.bz2 - name: cache ccache id: cache-ccache uses: actions/cache@v4 with: # TODO: use environment variable $HOME/.ccache path: /home/runner/.ccache key: ${{ matrix.os }}-${{ matrix.debian }}-ccache-${{ github.sha }} restore-keys: ${{ matrix.os }}-${{ matrix.debian }}-ccache- - name: Get Snapweb run: | wget https://github.com/badaix/snapweb/releases/download/${SNAPWEB_VERSION}/snapweb.zip unzip snapweb.zip -d snapweb - name: Create deb package env: # TODO: use environment variable $HOME/.ccache CCACHE_DIR: /home/runner/.ccache run: | fakeroot make -f debian/rules CMAKEFLAGS="-DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DBOOST_ROOT=$GITHUB_WORKSPACE/${{env.BOOST}} -DCMAKE_BUILD_TYPE:STRING=Release -DREVISION=${{ github.sha }} -DBUILD_WITH_PULSE=OFF -DSNAPWEB_DIR:STRING=$GITHUB_WORKSPACE/snapweb" binary rename 's/_${{ matrix.arch }}/_without-pulse_${{ matrix.arch }}/g' ../snapclient*_${{ matrix.arch }}.deb fakeroot make -f debian/rules clean fakeroot make -f debian/rules CMAKEFLAGS="-DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DBOOST_ROOT=$GITHUB_WORKSPACE/${{env.BOOST}} -DCMAKE_BUILD_TYPE:STRING=Release -DREVISION=${{ github.sha }} -DSNAPWEB_DIR:STRING=$GITHUB_WORKSPACE/snapweb" binary - name: Archive artifacts uses: actions/upload-artifact@v4 with: name: snapcast_${{ matrix.arch }}-debian-${{matrix.debian}}-${{ github.sha }} path: ${{env.PARENT_DIR}}/snap*_${{ matrix.arch }}.deb # mac: # strategy: # fail-fast: false # matrix: # xcode: ['11'] # runs-on: macos-latest # name: mac (xcode ${{ matrix.xcode }}) # steps: # - name: Checkout # uses: actions/checkout@v4 # - name: Checkout Snapcast # uses: actions/checkout@v4 # with: # repository: badaix/snapcast # path: src/snapcast # ref: ${{ env.VERSION }} # - name: Setup environment # run: | # BOOST_DOT_VERSION=$(echo ${BOOST_VERSION} | sed 's/_/./g') # echo "BOOST_DOT_VERSION=$BOOST_DOT_VERSION" >> $GITHUB_ENV # echo "BOOST=boost_${BOOST_VERSION}" >> $GITHUB_ENV # - name: Get dependencies # run: brew install pkgconfig libsoxr ccache expat # - name: Cache boost # id: cache-boost # uses: actions/cache@v4 # with: # path: ${{env.BOOST}} # key: ${{ runner.os }}-boost # - name: Get boost # if: steps.cache-boost.outputs.cache-hit != 'true' # run: | # wget https://boostorg.jfrog.io/artifactory/main/release/${{env.BOOST_DOT_VERSION}}/source/${{env.BOOST}}.tar.bz2 # tar xjf ${{env.BOOST}}.tar.bz2 # - name: Cache ccache # id: cache-ccache # uses: actions/cache@v4 # with: # path: /Users/runner/.ccache # key: ${{ runner.os }}-ccache-${{ github.sha }} # restore-keys: ${{ runner.os }}-ccache- # #- name: ccache dump config # # run: ccache -p # - name: configure # run: cmake -S $GITHUB_WORKSPACE/src/snapcast -B build -DBOOST_ROOT=$GITHUB_WORKSPACE/${{env.BOOST}} -DCMAKE_BUILD_TYPE=Release -DREVISION=${{ github.sha }} -DWERROR=ON -DBUILD_TESTS=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_FLAGS="-I/usr/local/include -Wno-deprecated-declarations" # - name: build # run: cmake --build build --parallel 3 # rpm: # if: ${{ false }} # disable for now # strategy: # fail-fast: false # matrix: # image: # - 34 # - 35 # os: # - ubuntu-latest # - self-hosted-rpi4 # include: # - os: ubuntu-latest # arch: "x86_64" # - os: self-hosted-rpi4 # arch: "armv7hl" # runs-on: ${{ matrix.os }} # name: rpm (${{ matrix.arch }}, fedora ${{ matrix.image }}) # container: # image: fedora:${{matrix.image}} # steps: # - name: Get dependencies # run: dnf -y update && dnf -y install wget git rpm-build gcc-c++ cmake boost-devel alsa-lib-devel avahi-devel libatomic libvorbis-devel opus-devel pulseaudio-libs-devel flac-devel soxr-devel libstdc++-static expat-devel # - name: Checkout # uses: actions/checkout@v4 # - name: Checkout Snapcast # uses: actions/checkout@v4 # with: # repository: badaix/snapcast # path: src/snapcast # ref: ${{ env.VERSION }} # - name: Create rpm package # run: | # mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} # cp rpm/* ~/rpmbuild/SOURCES/ # tar -C $GITHUB_WORKSPACE/src/ -czvf ~/rpmbuild/SOURCES/snapcast.tar.gz snapcast # rpmbuild --nodebuginfo --define '_reversion ${{ github.sha }}' --define '_version ${{ env.VERSION }}' -bb ~/rpmbuild/SOURCES/snapcast.spec # - name: Archive artifacts # uses: actions/upload-artifact@v4 # with: # name: snapcast_${{ matrix.arch }}-fedora-${{matrix.image}}-${{ github.sha }} # path: ~/rpmbuild/RPMS/${{ matrix.arch }}/snap*.rpm win: runs-on: windows-2019 name: win steps: - name: Checkout uses: actions/checkout@v4 - name: Checkout Snapcast uses: actions/checkout@v4 with: repository: badaix/snapcast path: src/snapcast ref: ${{ env.VERSION }} - name: Cache dependencies id: cache-dependencies uses: actions/cache@v4 with: #path: ${VCPKG_INSTALLATION_ROOT}\installed path: c:\vcpkg\installed key: ${{ runner.os }}-dependencies - name: Get dependenciesenv if: steps.cache-dependencies.outputs.cache-hit != 'true' run: vcpkg.exe install libflac libvorbis soxr opus boost-asio --triplet x64-windows - name: configure run: | echo vcpkg installation root: $env:VCPKG_INSTALLATION_ROOT cmake -S . -B build -G "Visual Studio 16 2019" -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" -DVCPKG_TARGET_TRIPLET="x64-windows" -DCMAKE_BUILD_TYPE="Release" -DREVISION="${{ github.sha }}" -DWERROR=ON -DBUILD_TESTS=ON - name: build run: cmake --build build --config Release --parallel 3 --verbose - name: installer run: | copy ${env:VCPKG_INSTALLATION_ROOT}\installed\x64-windows\bin\FLAC.dll bin\Release\ copy ${env:VCPKG_INSTALLATION_ROOT}\installed\x64-windows\bin\ogg.dll bin\Release\ copy ${env:VCPKG_INSTALLATION_ROOT}\installed\x64-windows\bin\opus.dll bin\Release\ copy ${env:VCPKG_INSTALLATION_ROOT}\installed\x64-windows\bin\vorbis.dll bin\Release\ copy ${env:VCPKG_INSTALLATION_ROOT}\installed\x64-windows\bin\soxr.dll bin\Release\ copy "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Redist\MSVC\v142\vc_redist.x64.exe" bin\Release\ - name: Archive artifacts uses: actions/upload-artifact@v4 with: name: snapcast_win64-${{ github.sha }} path: | bin\Release\snapclient.exe bin\Release\FLAC.dll bin\Release\ogg.dll bin\Release\opus.dll bin\Release\vorbis.dll bin\Release\soxr.dll bin\Release\vc_redist.x64.exe snapcast-0.28.0/.gitignore000066400000000000000000000017261461051111600154070ustar00rootroot00000000000000# 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 debian/tmp obj-x86_64-linux-gnu # clangd .cache compile_commands.json # misc notes.txt sanitizer-suppressions.txt snapserver.conf extras/package/debian/snap*.debhelper.log snapcast-0.28.0/CMakeLists.txt000066400000000000000000000236511461051111600161600ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project( snapcast LANGUAGES CXX VERSION 0.28.0) set(PROJECT_DESCRIPTION "Multiroom 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 (in test/snapcast_test)" OFF) option(WERROR "Treat warnings as errors" OFF) option(ASAN "Enable AddressSanitizer" OFF) option(TSAN "Enable ThreadSanitizer" OFF) option(UBSAN "Enable UndefinedBehaviorSanitizer" OFF) option(TIDY "Enable clang tidy" OFF) if(REVISION) add_compile_definitions(REVISION=\"${REVISION}\") endif() if(TIDY) find_program(CLANG_TIDY "clang-tidy") if(CLANG_TIDY) set(CMAKE_CXX_CLANG_TIDY "clang-tidy") endif() 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) endif() if(MSVC) # warning level 4 and all warnings as errors warning C4505: 'getArch': # unreferenced local function has been removed warning C4458: declaration of # 'size' hides class member warning C4459: declaration of 'query' hides global # declaration add_compile_options(/W4 /wd4458 /wd4459 /wd4505) if(WERROR) add_compile_options(/WX) endif() else() # lots of warnings and all warnings as errors add_compile_options(-Wall -Wextra -pedantic -Wno-unused-function) if(MACOSX) add_compile_options(-Wno-deprecated-declarations) endif() if(WERROR) add_compile_options(-Werror) endif() if(ASAN) add_compile_options(-fsanitize=address) add_link_options(-fsanitize=address) endif() if(TSAN) add_compile_options(-fsanitize=thread) add_link_options(-fsanitize=thread) endif() if(UBSAN) add_compile_options(-fsanitize=undefined) add_link_options(-fsanitize=undefined) endif() endif() include(GNUInstallDirs) include(${CMAKE_SOURCE_DIR}/cmake/cppcheck.cmake) include(${CMAKE_SOURCE_DIR}/cmake/reformat.cmake) if(NOT WIN32) option(BUILD_SERVER "Build Snapserver" ON) # no Windows server for now endif() 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) option(BUILD_WITH_EXPAT "Build with EXPAT support" ON) option(BUILD_WITH_PULSE "Build with PulseAudio 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() # 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_compile_definitions(VERSION="${PROJECT_VERSION}") if(NOT ANDROID) 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) endif() # Configure compiler options set(CMAKE_CXX_STANDARD 17) include(${CMAKE_SOURCE_DIR}/cmake/TargetArch.cmake) target_architecture(HOST_ARCH) # message(STATUS "System name: ${CMAKE_SYSTEM_NAME}") message(STATUS "Architecture: ${HOST_ARCH}") # message(STATUS "System processor: ${CMAKE_SYSTEM_PROCESSOR}") if(ARCH) message(STATUS "Using arch: ${ARCH}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=${ARCH}") endif() include(CheckAtomic) include(TestBigEndian) test_big_endian(BIGENDIAN) if(${BIGENDIAN}) add_compile_definitions(IS_BIG_ENDIAN) endif(${BIGENDIAN}) # Check dependencies if(NOT WIN32) # no PkgConfig on Windows... find_package(PkgConfig REQUIRED) endif() find_package(Threads REQUIRED) include(CMakePushCheckState) include(CheckIncludeFileCXX) 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_compile_definitions(NO_CPP11_STRING) endif() if(NOT WIN32 AND NOT ANDROID) if(MACOSX) set(BONJOUR_FOUND true) if(BONJOUR_FOUND) add_compile_definitions(HAS_BONJOUR) endif(BONJOUR_FOUND) add_compile_definitions(FREEBSD MACOS HAS_DAEMON) link_directories("/usr/local/lib") list(APPEND INCLUDE_DIRS "/usr/local/include") else() pkg_search_module(ALSA REQUIRED alsa) if(ALSA_FOUND) add_compile_definitions(HAS_ALSA) endif(ALSA_FOUND) if(BUILD_WITH_PULSE) pkg_search_module(PULSE libpulse) if(PULSE_FOUND) add_compile_definitions(HAS_PULSE) endif(PULSE_FOUND) endif(BUILD_WITH_PULSE) if(BUILD_WITH_AVAHI) pkg_search_module(AVAHI avahi-client) if(AVAHI_FOUND) add_compile_definitions(HAS_AVAHI) else() message(STATUS "avahi-client not found") endif(AVAHI_FOUND) endif(BUILD_WITH_AVAHI) add_compile_definitions(HAS_DAEMON) if(FREEBSD) add_compile_definitions(FREEBSD) link_directories("/usr/local/lib") list(APPEND INCLUDE_DIRS "/usr/local/include") endif() endif() pkg_search_module(SOXR soxr) if(SOXR_FOUND) add_compile_definitions(HAS_SOXR) else() message(STATUS "soxr not found") endif(SOXR_FOUND) if(BUILD_WITH_FLAC) pkg_search_module(FLAC flac) if(FLAC_FOUND) add_compile_definitions(HAS_FLAC) else() message(STATUS "flac not found") endif(FLAC_FOUND) endif() if(BUILD_WITH_VORBIS OR BUILD_WITH_TREMOR) pkg_search_module(OGG ogg) if(OGG_FOUND) add_compile_definitions(HAS_OGG) else() message(STATUS "ogg not found") endif(OGG_FOUND) endif() if(BUILD_WITH_VORBIS) pkg_search_module(VORBIS vorbis) if(VORBIS_FOUND) add_compile_definitions(HAS_VORBIS) endif(VORBIS_FOUND) endif() if(BUILD_WITH_TREMOR) pkg_search_module(TREMOR vorbisidec) if(TREMOR_FOUND) add_compile_definitions(HAS_TREMOR) endif(TREMOR_FOUND) endif() if((BUILD_WITH_VORBIS OR BUILD_WITH_TREMOR) AND NOT VORBIS_FOUND AND NOT TREMOR_FOUND) message(STATUS "tremor and vorbis not found") endif() if(BUILD_WITH_VORBIS) pkg_search_module(VORBISENC vorbisenc) if(VORBISENC_FOUND) add_compile_definitions(HAS_VORBIS_ENC) else() message(STATUS "vorbisenc not found") endif(VORBISENC_FOUND) endif() if(BUILD_WITH_OPUS) pkg_search_module(OPUS opus) if(OPUS_FOUND) add_compile_definitions(HAS_OPUS) else() message(STATUS "opus not found") endif(OPUS_FOUND) endif() if(BUILD_WITH_EXPAT) pkg_search_module(EXPAT expat) if(EXPAT_FOUND) add_compile_definitions(HAS_EXPAT) else() message(STATUS "expat not found") endif(EXPAT_FOUND) endif() endif() if(NOT ANDROID) find_package(Boost 1.74 REQUIRED) else() find_package(oboe REQUIRED CONFIG) find_package(flac REQUIRED CONFIG) find_package(ogg REQUIRED CONFIG) find_package(opus REQUIRED CONFIG) find_package(soxr REQUIRED CONFIG) find_package(tremor REQUIRED CONFIG) find_package(boost REQUIRED CONFIG) add_compile_definitions(HAS_OBOE) add_compile_definitions(HAS_OPENSL) add_compile_definitions(HAS_FLAC) add_compile_definitions(HAS_OGG) add_compile_definitions(HAS_OPUS) add_compile_definitions(HAS_SOXR) add_compile_definitions(HAS_TREMOR) endif() add_compile_definitions(BOOST_ERROR_CODE_HEADER_ONLY BOOST_ASIO_NO_TS_EXECUTORS) if(WIN32) include(FindPackageHandleStandardArgs) set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) find_path(FLAC_INCLUDE_DIRS FLAC/all.h) find_library(FLAC_LIBRARIES FLAC) find_package_handle_standard_args(FLAC REQUIRED FLAC_INCLUDE_DIRS FLAC_LIBRARIES) find_path(OGG_INCLUDE_DIRS ogg/ogg.h) find_library(OGG_LIBRARIES ogg) find_package_handle_standard_args(Ogg REQUIRED OGG_INCLUDE_DIRS OGG_LIBRARIES) find_path(VORBIS_INCLUDE_DIRS vorbis/vorbisenc.h) find_library(VORBIS_LIBRARIES vorbis) find_package_handle_standard_args(Vorbis REQUIRED VORBIS_INCLUDE_DIRS VORBIS_LIBRARIES) find_path(OPUS_INCLUDE_DIRS opus/opus.h) find_library(OPUS_LIBRARIES opus) find_package_handle_standard_args(Opus REQUIRED OPUS_INCLUDE_DIRS OPUS_LIBRARIES) find_path(SOXR_INCLUDE_DIRS soxr.h) find_library(SOXR_LIBRARIES soxr) find_package_handle_standard_args(Soxr REQUIRED SOXR_INCLUDE_DIRS SOXR_LIBRARIES) add_compile_definitions( NTDDI_VERSION=0x06020000 _WIN32_WINNT=0x0602 WINVER=0x0602 WINDOWS WIN32_LEAN_AND_MEAN UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) add_compile_definitions( HAS_OGG HAS_VORBIS HAS_FLAC HAS_VORBIS_ENC HAS_OPUS HAS_WASAPI HAS_SOXR) endif() list(APPEND CMAKE_REQUIRED_INCLUDES "${INCLUDE_DIRS}") # include(${CMAKE_SOURCE_DIR}/cmake/SystemdService.cmake) add_subdirectory(common) if(BUILD_SERVER) add_subdirectory(server) endif() if(BUILD_CLIENT) add_subdirectory(client) endif() if(BUILD_TESTS) add_subdirectory(test) endif(BUILD_TESTS) snapcast-0.28.0/CMakePresets.json000066400000000000000000000112071461051111600166330ustar00rootroot00000000000000{ "version": 3, "cmakeMinimumRequired": { "major": 3, "minor": 21, "patch": 0 }, "configurePresets": [ { "name": "default", "binaryDir": "${sourceDir}/build", "generator": "Ninja", "hidden": true, "cacheVariables": { "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", "CMAKE_BUILD_TYPE": "Debug" } }, { "name": "linux", "displayName": "Linux", "inherits": "default", "condition": { "lhs": "${hostSystemName}", "type": "equals", "rhs": "Linux" }, "cacheVariables": { "CMAKE_C_COMPILER": "gcc", "CMAKE_CXX_COMPILER": "g++" } }, { "name": "windows", "inherits": "default", "architecture": { "value": "x64", "strategy": "external" }, "toolset": { "value": "host=x64", "strategy": "external" }, "condition": { "lhs": "${hostSystemName}", "type": "equals", "rhs": "Windows" }, "cacheVariables": { "CMAKE_C_COMPILER": "cl", "CMAKE_CXX_COMPILER": "cl" }, "vendor": { "microsoft.com/VisualStudioSettings/CMake/1.0": { "hostOS": [ "Windows" ] } } }, { "name": "macos", "displayName": "macOS", "inherits": "default", "condition": { "lhs": "${hostSystemName}", "type": "equals", "rhs": "Darwin" } }, { "name": "android", "inherits": "default", "hidden": true, "condition": { "lhs": "$env{ANDROID_NDK_HOME}", "type": "notEquals", "rhs": "" }, "toolchainFile": "$env{VCPKG_HOME}/scripts/buildsystems/vcpkg.cmake", "cacheVariables": { "CMAKE_SYSTEM_NAME": "Android", "CMAKE_ANDROID_NDK": "$env{ANDROID_NDK_HOME}", "VCPKG_CHAINLOAD_TOOLCHAIN_FILE": "$env{ANDROID_NDK_HOME}/build/cmake/android.toolchain.cmake" } }, { "name": "android-x86", "displayName": "Android x86", "inherits": "android", "cacheVariables": { "CMAKE_ANDROID_ARCH_ABI": "x86", "VCPKG_TARGET_TRIPLET": "x86-android" } }, { "name": "android-x86_64", "displayName": "Android x86_64", "inherits": "android", "cacheVariables": { "CMAKE_ANDROID_ARCH_ABI": "x86_64", "VCPKG_TARGET_TRIPLET": "x64-android" } }, { "name": "android-armeabi-v7a", "displayName": "Android armeabi-v7a", "inherits": "android", "cacheVariables": { "CMAKE_ANDROID_ARCH_ABI": "armeabi-v7a", "VCPKG_TARGET_TRIPLET": "arm-android" } }, { "name": "android-arm64-v8a", "displayName": "Android arm64-v8a", "inherits": "android", "cacheVariables": { "CMAKE_ANDROID_ARCH_ABI": "arm64-v8a", "VCPKG_TARGET_TRIPLET": "arm64-android" } } ], "buildPresets": [ { "name": "linux", "configurePreset": "linux", "displayName": "Linux" }, { "name": "windows", "configurePreset": "windows", "displayName": "x64" }, { "name": "macos", "configurePreset": "macos", "displayName": "macOS" }, { "name": "android-x86", "configurePreset": "android-x86", "displayName": "x86" }, { "name": "android-x86_64", "configurePreset": "android-x86_64", "displayName": "x86_64" }, { "name": "android-armeabi-v7a", "configurePreset": "android-armeabi-v7a", "displayName": "armeabi-v7a" }, { "name": "android-arm64-v8a", "configurePreset": "android-arm64-v8a", "displayName": "arm64-v8a" } ] } snapcast-0.28.0/CONTRIBUTING.md000066400000000000000000000111621461051111600156430ustar00rootroot00000000000000# Contributing ## Engaging in Our Project You can contribute in several ways: * Contribute code for new features, bugfixes, or documentation (see below) * Help testing the latest features. Nightly builds are available in [Actions](https://github.com/badaix/snapcast/actions) * Star the project * Donate on [PayPal](https://www.paypal.me/badaix) * Spread the word: blog about Snapcast, tell your friends ... We use GitHub to manage reviews of pull requests. * If you are a new contributor, see: [Steps to Contribute](#steps-to-contribute) * Before implementing your change, create an issue that describes the problem you would like to solve or the code that should be enhanced. Please note that you are willing to work on that issue. * The team will review the issue and decide whether it should be implemented as a Pull Request. In that case, they will assign the issue to you. If the team decides against picking up the issue, it will be closed with a proper explanation. ## Steps to Contribute Should you wish to work on an issue, please claim it first by commenting on the GitHub issue that you want to work on. This is to prevent duplicated efforts from other contributors on the same issue. Only start working on the Pull Request after the team assigned the issue to you to avoid unnecessary efforts. If you have questions about one of the issues, please comment on them, and one of the maintainers will clarify. We kindly ask you to follow the [Pull Request Checklist](#Pull-Request-Checklist) to ensure reviews can happen accordingly. ## Contributing Code You are welcome to contribute code in order to fix a bug or to implement a new feature that is logged as an issue. Only start working on the Pull Request after the team assigned the issue to you to avoid unnecessary efforts. Please note that Snapweb related contributions should be made in the [Snapweb project](https://github.com/badaix/snapweb). The following rule governs code contributions: * Contributions must be licensed under the [GPL-3.0 License](LICENSE) * This project loosely follows the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) * For better compatibility with embedded toolchains, the used C++ standard should be limited to C++17 * Code should be formatted by running `make reformat` ## Contributing Documentation You are welcome to contribute documentation to the project. The following rule governs documentation contributions: * Contributions must be licensed under the same license as code, the [GPL-3.0 License](LICENSE) ## Pull Request Checklist * Branch from the `develop` branch and ensure it is up to date with the current `develop` branch before submitting your pull request. If it doesn't merge cleanly with `develop`, you may be asked to resolve the conflicts. Pull requests to master will be closed. * Commits should be as small as possible while ensuring that each commit is correct independently (i.e., each commit should compile and pass tests). * Pull requests must not contain compiled sources (already set by the default .gitignore) or binary files * Test your changes as thoroughly as possible before you commit them. Preferably, automate your test by unit/integration tests. If tested manually, provide information about the test scope in the PR description (e.g. “Test passed: Upgrade version from 0.42 to 0.42.23.”). * Create _Work In Progress [WIP]_ pull requests only if you need clarification or an explicit review before you can continue your work item. * If your patch is not getting reviewed or you need a specific person to review it, you can @-reply a reviewer asking for a review in the pull request or a comment, or you can ask for a review by contacting us via [email](mailto:snapcast@badaix.de). * Post review: * If a review requires you to change your commit(s), please test the changes again. * Amend the affected commit(s) and force push onto your branch. * Set respective comments in your GitHub review to resolved. * Create a general PR comment to notify the reviewers that your amendments are ready for another round of review. ## Issues and Planning * We use GitHub issues to track bugs and enhancement requests. * Please provide as much context as possible when you open an issue. The information you provide must be comprehensive enough to reproduce that issue for the assignee. * Attach a log file (preferably inline as code block) if necessary. Use `debug` log level (`snapclient --logfilter debug`, `snapserver --logging.filter debug`). * Please apply one or more applicable [labels](https://github.com/badaix/snapcast/labels) to your issue so that all community members are able to cluster the issues better. snapcast-0.28.0/LICENSE000066400000000000000000001045061461051111600144240ustar00rootroot00000000000000 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.28.0/README.md000066400000000000000000000315621461051111600146770ustar00rootroot00000000000000# Snapcast ![Snapcast](doc/Snapcast_800.png#gh-light-mode-only) ![Snapweb-Dark](doc/Snapcast_800_dark.png#gh-dark-mode-only) **S**y**n**chronous **a**udio **p**layer [![CI](https://github.com/badaix/snapcast/actions/workflows/ci.yml/badge.svg)](https://github.com/badaix/snapcast/actions/workflows/ci.yml) [![Github Releases](https://img.shields.io/github/release/badaix/snapcast.svg)](https://github.com/badaix/snapcast/releases) [![GitHub Downloads](https://img.shields.io/github/downloads/badaix/snapcast/total)](https://github.com/badaix/snapcast/releases) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/badaix) Snapcast is a multiroom 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 multiroom solution. Audio is captured by the server and routed to the connected clients. Several players can feed audio to the server in parallel and clients can be grouped to play the same audio stream. 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/). ![Overview](doc/Overview.png) ## How does it work The Snapserver reads PCM chunks from configurable stream sources: - **Named pipe**, e.g. `/tmp/snapfifo` - **ALSA** to capture line-in, microphone, alsa-loop (to capture audio from other players) - **TCP** - **stdout** of a process - Many more The chunks are 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 chunks are 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 a system dependend low level audio API (e.g. ALSA) at the appropriate time. Time deviations are corrected by playing faster/slower, which is done by removing/duplicating single samples (a sample at 48kHz has a duration of ~0.02ms). Typically the deviation is below 0.2ms. For more information on the binary protocol, please see the [documentation](doc/binary_protocol.md). ## Installation You can either install Snapcast from a prebuilt package (recommended for new users), or build and install snapcast from source. ### Install Linux packages (recommended for beginners) Snapcast packages are available for several Linux distributions: - [Debian](doc/install.md#debian) - [OpenWrt](doc/install.md#openwrt) - [Alpine Linux](doc/install.md#alpine-linux) - [Archlinux](doc/install.md#archlinux) - [Void Linux](doc/install.md#void-linux) ### Nightly builds There are debian packages of automated builds for `armhf`, `arm64` and `amd64` in [Snapcast Actions - Package workflow](https://github.com/badaix/snapcast/actions/workflows/package.yml). Download and extract the archive for your architecture and follow the [debian installation instructions](doc/install.md#debian). ### Install using Homebrew On macOS and Linux, snapcast can be installed using [Homebrew](https://brew.sh): ```bash brew install snapcast ``` ### 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) - [Windows](doc/build.md#windows-vcpkg) ## 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. ### Server The server configuration is done in `/etc/snapserver.conf`. Different audio sources can by configured in the `[stream]` section with a list of `source` options, e.g.: ```ini [stream] source = pipe:///tmp/snapfifo?name=Radio&sampleformat=48000:16:2&codec=flac source = file:///home/user/Musik/Some%20wave%20file.wav?name=File ``` Available stream sources are: - [pipe](doc/configuration.md#pipe): read audio from a named pipe - [alsa](doc/configuration.md#alsa): read audio from an alsa device - [librespot](doc/configuration.md#librespot): launches librespot and reads audio from stdout - [airplay](doc/configuration.md#airplay): launches airplay and read audio from stdout - [file](doc/configuration.md#file): read PCM audio from a file - [process](doc/configuration.md#process): launches a process and reads audio from stdout - [tcp](doc/configuration.md#tcp-server): receives audio from a TCP socket, can act as client or server - [meta](doc/configuration.md#meta): read and mix audio from other stream sources ### Client The client will use as audio backend the system's low level audio API to have the best possible control and most precise timing to achieve perfectly synced playback. Available audio backends are configured using the `--player` command line parameter: | Backend | OS | Description | Parameters | | --------- | ------- | ------------ | ---------- | | alsa | Linux | ALSA | `buffer_time=` (default 80, min 10)
`fragments=` (default 4, min 2) | | pulse | Linux | PulseAudio | `buffer_time=` (default 100, min 10)
`server=` - default not-set: use the default server
`property==` set PA property, can be used multiple times (default `media.role=music`) | | oboe | Android | Oboe, using OpenSL ES on Android 4.1 and AAudio on 8.1 | | | opensl | Android | OpenSL ES | | | coreaudio | macOS | Core Audio | | | wasapi | Windows | Windows Audio Session API | | | file | All | Write audio to file | `filename=` (`` = `stdout`, `stderr`, `null` or a filename)
`mode=[w|a]` (`w`: write (discarding the content), `a`: append (keeping the content) | Parameters are appended to the player name, e.g. `--player alsa:buffer_time=100`. Use `--player :?` to get a list of available options. For some audio backends you can configure the PCM device using the `-s` or `--soundcard` parameter, the device is chosen by index or name. Available PCM devices can be listed with `-l` or `--list` If you are running MPD and Shairport-sync into a soundcard that only supports 48000 sample rate, you can use `--sampleformat ` and the snapclient will resample the audio from shairport-sync, for example, which is 44100 (i.e. `--sampleformat 48000:16:*`) ## Test You can test your installation by copying random data into the server's fifo file 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] source = 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/control.md) over plain TCP, HTTP, or Websockets: - Set client's volume - Mute clients - Rename clients - Assign a client to a stream - Manage groups - ... ### WebApp The server is shipped with [Snapweb](https://github.com/badaix/snapweb), this WebApp can be reached under `http://:1780`. ![Snapweb-Light](https://raw.githubusercontent.com/badaix/snapweb/master/snapweb_light.png#gh-light-mode-only) ![Snapweb-Dark](https://raw.githubusercontent.com/badaix/snapweb/master/snapweb_dark.png#gh-dark-mode-only) ### Android client There is an Android client [snapdroid](https://github.com/badaix/snapdroid) available in [Releases](https://github.com/badaix/snapdroid/releases/latest) and on [Google Play](https://play.google.com/store/apps/details?id=de.badaix.snapcast) ![Snapcast for Android](doc/snapcast_android_scaled.png) ### Contributions 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 and a [snapcast python plugin for Domoticz](https://github.com/akamming/domoticz-snapcast) to integrate a Snapcast controller into the [Domoticz](https://domoticz.com/) 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. For Windows, there's [Snap.Net](https://github.com/stijnvdb88/snap.net), a control client and player. It runs in the tray and lets you adjust client volumes with just a few clicks. The player simplifies setting up snapclient to play your music through multiple Windows sound devices simultaneously: pc speakers, hdmi audio, any usb audio devices you may have, etc. Snap.Net also runs on Android, and has limited support for iOS. ## 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) - [VLC](doc/player_setup.md#vlc) ## 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 96kHz 24bit) - [X] **Groups** support multiple Groups of clients ("Zones") - [X] **Ports** Snapclient for Windows, Mac OS X,... - [ ] **JSON-RPC** Possibility to add, remove, rename streams - [ ] **Protocol specification** Snapcast binary streaming protocol, JSON-RPC protocol snapcast-0.28.0/TODO.md000066400000000000000000000013101461051111600144730ustar00rootroot00000000000000TODO ==== General ------- - Update Readme.md - JsonRPC documentation - Server ping client? - UDP based audio streaming Server ------ - [fd stream](https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer-plugins/html/gstreamer-plugins-fdsink.html) - gstreamer snapcast sink plugin? - "sync" option for streams (realtime reading vs read as much as available) - #402: Add meta stream that reads the input of other streams (in some fallback hierarchy manner: when the first one plays, use this signal, else if the second is playing, take this, ...). Client ------ - Add option to not play in sync, i.e. not change the tempo Issues ------ - Android clean data structures after changing the Server snapcast-0.28.0/changelog.md000066400000000000000000000571411461051111600156720ustar00rootroot00000000000000# Snapcast changelog ## Version 0.28.0 ### Features - Server: Use filename as title for FileStreams - Client: Loop through resolved server IPs during connect (Issue #1216) ### Bugfixes - Server: Fix noise caused by reading half samples (Issue #1170) - Server: Check open syscall error in PipeStream::do_connect (PR #1150) - Server: Tweak Airplay support (#1102) - Server: Lower log severity for shairport-sync (Issue #891) - Server: Emits notifications for streams with codec=null (Is11sue #1205) - Server: Fix delayed switching of meta streams (Issue #1187) - Server: Mixer script calls piling up (Issue #1174) - Server: Mixer script creates zombie processes (Issue #1157) - Improve connect handling in meta_mopidy.py - Improve connect handling in meta_librespot-java.py - Fix cppcheck issues ### General - CI: Build debian bookworm and bullseye packages for amd64, arm and arm64 - CI: Add cppcheck static analysis - Update documentation (PR #1130, PR #1067) - Delete deprecated Makefiles, CMake is the only supported buildsystem - Snapweb: Update to v0.7.0 _Johannes Pohl Fri, 19 Apr 2024 00:13:37 +0200_ ## Version 0.27.0 ### Features - Server: Configurable default volume for new clients (Issue #910, PR #1024) - Server: New control script for mopidy: meta_mopidy.py - Server: New control script for librespot java: meta_librespot-java.py - Server: Add "mute" stream property ### Bugfixes - Server: Fix random crash with meta stream (Issue #966) - Server: Fix compatibility with librespot 0.5-dev (Issue #1063, #1074, #1042) - Server: Not terminate on malformed json messages (Issue #1049) - Server: Fix random segfault (Issue #1047) - Server: Fix growing delay on input stream (Issue #1014) - Server: Fix segfault with Librespot on Alpine (Issue #1026) - Server: meta_mpd.py is installed with 755 (Issue #1021, #970) - Server: Add list of dependecies to meta_mpd.py (Issue #971) - Server: meta_mpd.py stopped working (Issue #997) - Client: Not terminate if codec is "null" (Issue #1076) - Fix test failures (Issue #961) ### General - Fix compilation on macOS with Xcode 13.4.1 (Issue #1028) - Fix compilation with boost 1.81.0 (Issue #1082) - Remove debhelper files from project (moved to SnapOS project) - SnapOs uses containers to build deb packages (solves Issue #968) - Snapweb: Update to v0.5.0 _Johannes Pohl Sun, 05 Feb 2023 00:13:37 +0200_ ## Version 0.26.0 ### Features - Client: Disconnect from pulse when no audio is available (Issue #927, PR #931) - Server: New Metadata API for audio streams (Issue #803, #953) - Server: New Control API for audio streams (Issue #954) - Server: Lowered minimum buffer from 400ms to 20ms (Issue #329) ### Bugfixes - Server: systemd.unit starts server after network-online (Issue #950) ### General - Update documentation (Issue #804, PR #945, PR #951) - Snapweb: Update to v0.4.0 _Johannes Pohl Wed, 22 Dec 2021 00:13:37 +0200_ ## Version 0.25.0 ### Features - Client: Editable PulseAudio properties, e.g. media.role=music (Issue #829) - Server: Configurable amplitute for silence detection in alsa stream (Issue #846) ### Bugfixes - Client: Fix crash on Windows when system volume changes (PR #838) - Client: Removed a log message to stdout for file player backend (Issue #681) - Server: Fix percent-decoding for stream URIs (Issue #850) - Server: Fix double quotes in Airplay device names (Issue #851) - Server: Fix crash when feeding a 16 bit signal into 24 bit flac (Issue #866) ### General - Server: less verbose librespot logging (Issue #874) - Snapweb: Update to v0.3.0 - Add unit tests to the project _Johannes Pohl Sat, 15 May 2021 00:13:37 +0200_ ## Version 0.24.0 ### Features - Client: Configurable server for Pulseaudio backend (Issue #779) ### Bugfixes - Client: Fix dropouts in alsa player backend (Issue #774) - Client: Fix alsa player volume resetting to max (Issue #735) - Client: Fix noise while muted for Pulseaudio (Issue #785) - Client: Android support for opus readded (Issue #789) - Client: Fix host id for MacBook Pro (later 2016) (Issue #807) ### General - Snapweb: Update to v0.2.0 - Remove submodules with external libs from the git repository - Write version and revision (git sha) to log - Add documentation to the default files (Issue #791) _Johannes Pohl Sat, 27 Feb 2021 00:13:37 +0200_ ## Version 0.23.0 ### Features - Client: Add PulseAudio player backend (Issue #722) - Client: Configurable buffer time for alsa and pulse players - Server: If docroot is not configured, a default page is served (Issue #711) - Server: airplay source supports "password" parameter (Issue #754) ### Bugfixes - Server: airplay source deletes Shairport's meta pipe on exit (Issue #672) - Server: alsa source will not send silece when going idle (Issue #729) - Server: pipe source will not send silence after 3h idle (Issue #741) - Server: Fix build error on FreeBSD (Issue #752) - Client: "make install" will set correct user/group for snapclient (Issue #728) - Client: Fix printing UTF-8 device names on Windows (Issue #732) - Client: Fix stuttering on alsa player backend (Issue #722, #727) - Client: Terminate if host is not configured and mDNS is unavailable ### General - Server: Change librespot parameter "killall" default to false (Issue #746, #724) - Client: Android uses performance mode "none" to allow effects (Issue #766) - Snapweb: Update to v0.1.0 - Build: Update CMakeLists.txt to build Snapclient on Android _Johannes Pohl Sun, 10 Jan 2021 00:13:37 +0200_ ## Version 0.22.0 ### Features - Server: Add Meta stream source (Issue #402, #569, #666) - Client: Add file audio backend (Issue #681) ### Bugfixes - Add missing define for alsa stream to makefile (Issue #692) - Fix playback when plugging the headset on Android (Issue #699) - Server discards old chunks if not consumed (Issue #708) ### General - Less verbose logging during pipe reconnects (Issue #696) - Add null encoder for streams used only as input for meta streams - Snapweb: Change latency range to [-10s, 10s] (Issue #695) - Update Snapweb, including PR #11, #12, #13, Issues #16, #17 _Johannes Pohl Thu, 15 Oct 2020 00:13:37 +0200_ ## Version 0.21.0 ### Features - Server: Support for WebSocket streaming clients - Server: Install Snapweb web client (Issue #579) - Server: Resample input to 48000:16:2 when using opus codec - Server: Add Alsa stream source ### Bugfixes - make install will setup the snapserver home dir (Issue #643) - Client retries to open a blocked alsa device (Issue #652) ### General - debian package generation switched from make to CMake buildsystem - Reintroduce MACOS define, hopefully not breaking anything on macOS - Snapcast uses GitHub actions for automated CI/CD - CMake installs man files (Issue #507) - Update documentation (Issue #615, #617) _Johannes Pohl Sun, 13 Sep 2020 00:13:37 +0200_ ## Version 0.20.0 ### Features - Client: Windows support (Issue #24) - Client: add hardware mixer (Issue #318) - Client: add "script" and "none" mixer (Issue #302) - Client: add sharingmode for audio device (if supported) - Logging: configurable sink and filters (Issue #30, #561, #122, #559) - Librespot: add option "disable-audio-cache=[false|true]" ### Bugfixes - Fix build failure on FreeBSD (Issue #565) - Fix calling lsb_release multiple times (Issue #470) - Client: high CPU load and crash during playback (Issue #609, #628) - Client: improved handling of USB audio disconnects (Issue #64) - Client: latency is forgotten (Issue #476, #588, Snapdroid #11) - Client: fix segfault on mac when playback is paused (Issue #560) - Client: fix bonjour on mac reports empty IP (Issue #632) - Client: fix buzzing tone on Android (Issue #23, #24) - Server: fix crash if client disconnects during connect (Issue #639) - Server: fix reading metadata from shairport-sync (Issue #624) - Server: fix crash on FreeBSD if settings.json is empty (Issue #620) - Server: fix warning about unknown command line options (Issue #635) - Readme: openWrt documentation (Issue #633) - Fix setting the daemon's process priority (PR #448) ### General - Client: use less threads and thus less ressources - Update links to xiph externals (Issue #637, PR #616) _Johannes Pohl Sat, 13 Jun 2020 00:13:37 +0200_ ## Version 0.19.0 ### Features - Option to not kill all running librespot instances (PR #539) - Add Airplay cover art to metadata (PR #543) - Anroid: add support for Oboe audio backend - Server: configurable PID file (Issue #554) - Server: configurable persistant storage directory (Issue #554) - Server: config file options can be overwritten on command line - Client: PCM stream can be resampled using the "--sampleformat" option - Librespot: add option "autoplay=[false|true]" ### Bugfixes - Fix Airplay metadata, port selection and device names (PR #537) - Fix cmake build when libatomic is needed (PR #540) - Control: fix random crash (PR #543) ### General - ALSA: improved latency estimation for better sync - Improved audio synchronization - Faster initial sync after client start and reconnect - Less playback tempo adaptions and jitter (Issue #525) - Playback is robust against system time changes (Issue #522) - Less "resyncs" in stream reader that were causing audio dropouts - Control: quicker response to group volume changes - Server uses less memory when sending PCM data to a stalled connection _Johannes Pohl Sat, 14 Mar 2020 00:13:37 +0200_ ## 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 ### Bugfixes - 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.28.0/client/000077500000000000000000000000001461051111600146675ustar00rootroot00000000000000snapcast-0.28.0/client/CMakeLists.txt000066400000000000000000000075471461051111600174440ustar00rootroot00000000000000set(CLIENT_SOURCES client_connection.cpp controller.cpp snapclient.cpp stream.cpp time_provider.cpp decoder/pcm_decoder.cpp decoder/null_decoder.cpp player/player.cpp player/file_player.cpp) set(CLIENT_LIBRARIES ${CMAKE_THREAD_LIBS_INIT} ${ATOMIC_LIBRARY} common) set(CLIENT_INCLUDE ${Boost_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/client ${CMAKE_SOURCE_DIR}) if(MACOSX) # Bonjour if(BONJOUR_FOUND) list(APPEND CLIENT_SOURCES browseZeroConf/browse_bonjour.cpp) endif(BONJOUR_FOUND) # CoreAudio add_compile_definitions(HAS_COREAUDIO) list(APPEND CLIENT_SOURCES player/coreaudio_player.cpp) find_library(COREAUDIO_LIB CoreAudio) find_library(COREFOUNDATION_LIB CoreFoundation) find_library(IOKIT_LIB IOKit) find_library(AUDIOTOOLBOX_LIB AudioToolbox) list(APPEND CLIENT_LIBRARIES ${COREAUDIO_LIB} ${COREFOUNDATION_LIB} ${IOKIT_LIB} ${AUDIOTOOLBOX_LIB}) elseif(WIN32) list(APPEND CLIENT_SOURCES player/wasapi_player.cpp) list( APPEND CLIENT_LIBRARIES wsock32 ws2_32 avrt ksuser iphlpapi) elseif(NOT ANDROID) # 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) if(PULSE_FOUND) list(APPEND CLIENT_SOURCES player/pulse_player.cpp) list(APPEND CLIENT_LIBRARIES ${PULSE_LIBRARIES}) list(APPEND CLIENT_INCLUDE ${PULSE_INCLUDE_DIRS}) endif(PULSE_FOUND) endif(MACOSX) if(ANDROID) list(APPEND CLIENT_LIBRARIES oboe::oboe) list(APPEND CLIENT_LIBRARIES boost::boost) list(APPEND CLIENT_LIBRARIES flac::flac) list(APPEND CLIENT_LIBRARIES opus::opus) list(APPEND CLIENT_LIBRARIES tremor::tremor) list(APPEND CLIENT_LIBRARIES ogg::ogg) list(APPEND CLIENT_SOURCES player/oboe_player.cpp) list(APPEND CLIENT_SOURCES player/opensl_player.cpp) list(APPEND CLIENT_SOURCES decoder/flac_decoder.cpp) list(APPEND CLIENT_SOURCES decoder/ogg_decoder.cpp) list(APPEND CLIENT_SOURCES decoder/opus_decoder.cpp) list(APPEND CLIENT_LIBRARIES OpenSLES) else() # 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 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) 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) endif() include_directories(${CLIENT_INCLUDE}) if(ANDROID) add_executable(libsnapclient.so ${CLIENT_SOURCES}) target_link_libraries(libsnapclient.so ${CLIENT_LIBRARIES} log OpenSLES) else() add_executable(snapclient ${CLIENT_SOURCES}) target_link_libraries(snapclient ${CLIENT_LIBRARIES}) install( TARGETS snapclient COMPONENT client DESTINATION "${CMAKE_INSTALL_BINDIR}") install( FILES snapclient.1 COMPONENT client DESTINATION "${CMAKE_INSTALL_MANDIR}/man1") install( FILES etc/snapcast.svg COMPONENT client DESTINATION ${CMAKE_INSTALL_DATADIR}/pixmaps) endif() snapcast-0.28.0/client/browseZeroConf/000077500000000000000000000000001461051111600176365ustar00rootroot00000000000000snapcast-0.28.0/client/browseZeroConf/browse_avahi.cpp000066400000000000000000000177771461051111600230360ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "browse_avahi.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" // standard headers #include #include static AvahiSimplePoll* simple_poll = nullptr; static constexpr auto LOG_TAG = "Avahi"; BrowseAvahi::BrowseAvahi() : client_(nullptr), sb_(nullptr) { } BrowseAvahi::~BrowseAvahi() { cleanUp(); } void BrowseAvahi::cleanUp() { if (sb_ != nullptr) avahi_service_browser_free(sb_); sb_ = nullptr; if (client_ != nullptr) avahi_client_free(client_); client_ = nullptr; if (simple_poll != nullptr) 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) { auto* 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, LOG_TAG) << "(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, LOG_TAG) << "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, LOG_TAG) << "\t" << host_name << ":" << port << " (" << a << ")\n"; LOG(DEBUG, LOG_TAG) << "\tTXT=" << t << "\n"; LOG(DEBUG, LOG_TAG) << "\tProto=" << static_cast(protocol) << "\n"; LOG(DEBUG, LOG_TAG) << "\tcookie is " << avahi_string_list_get_service_cookie(txt) << "\n"; LOG(DEBUG, LOG_TAG) << "\tis_local: " << !((flags & AVAHI_LOOKUP_RESULT_LOCAL) == 0) << "\n"; LOG(DEBUG, LOG_TAG) << "\tour_own: " << !((flags & AVAHI_LOOKUP_RESULT_OUR_OWN) == 0) << "\n"; LOG(DEBUG, LOG_TAG) << "\twide_area: " << !((flags & AVAHI_LOOKUP_RESULT_WIDE_AREA) == 0) << "\n"; LOG(DEBUG, LOG_TAG) << "\tmulticast: " << !((flags & AVAHI_LOOKUP_RESULT_MULTICAST) == 0) << "\n"; LOG(DEBUG, LOG_TAG) << "\tcached: " << !((flags & AVAHI_LOOKUP_RESULT_CACHED) == 0) << "\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; auto* 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, LOG_TAG) << "(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, LOG_TAG) << "(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, static_cast(0), resolve_callback, userdata)) == nullptr) LOG(ERROR, LOG_TAG) << "Failed to resolve service '" << name << "': " << avahi_strerror(avahi_client_errno(browseAvahi->client_)) << "\n"; break; case AVAHI_BROWSER_REMOVE: LOG(INFO, LOG_TAG) << "(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, LOG_TAG) << "(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, LOG_TAG) << "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()) == nullptr) 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), static_cast(0), client_callback, this, &error)) == nullptr) 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, static_cast(0), browse_callback, this)) == nullptr) 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.28.0/client/browseZeroConf/browse_avahi.hpp000066400000000000000000000041651461051111600230260ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once class BrowseAvahi; // local headers #include "browse_mdns.hpp" // 3rd party headers #include #include #include #include #include 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_; }; snapcast-0.28.0/client/browseZeroConf/browse_bonjour.cpp000066400000000000000000000206301461051111600234020ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "browse_bonjour.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" // standard headers #include #include #ifdef WINDOWS #include #include #else #include #include #endif using namespace std; static constexpr auto LOG_TAG = "Bonjour"; struct DNSServiceRefDeleter { void operator()(DNSServiceRef* ref) { DNSServiceRefDeallocate(*ref); delete ref; } }; using DNSServiceHandle = std::unique_ptr; 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{}); { 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); } resultCollection.erase(std::remove_if(resultCollection.begin(), resultCollection.end(), [](const mDNSResult& res) { return res.ip.empty(); }), resultCollection.end()); if (resultCollection.empty()) return false; if (resultCollection.size() > 1) LOG(NOTICE, LOG_TAG) << "Multiple servers found. Using first" << endl; result = resultCollection.front(); return true; } #undef CHECKED snapcast-0.28.0/client/browseZeroConf/browse_bonjour.hpp000066400000000000000000000017611461051111600234130ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once class BrowseBonjour; // local headers #include "browse_mdns.hpp" // 3rd party headers #include class BrowseBonjour : public BrowsemDNS { public: bool browse(const std::string& serviceName, mDNSResult& result, int timeout) override; }; snapcast-0.28.0/client/browseZeroConf/browse_mdns.hpp000066400000000000000000000026001461051111600226670ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // standard headers #include #include enum IPVersion { IPv4 = 0, IPv6 = 1 }; struct mDNSResult { mDNSResult() : ip_version(IPv4), iface_idx(0), port(0), valid(false) { } 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" using BrowseZeroConf = BrowseAvahi; #elif defined(HAS_BONJOUR) #include "browse_bonjour.hpp" using BrowseZeroConf = BrowseBonjour; #endif snapcast-0.28.0/client/build_android.sh000077500000000000000000000012651461051111600200310ustar00rootroot00000000000000#/bin/sh export NDK_DIR="$1" export JNI_LIBS_DIR="$2" export TOOLCHAIN="$NDK_DIR/toolchains/llvm/prebuilt/linux-x86_64" export ARCH=x86 make clean; make TARGET=ANDROID -j 4; $TOOLCHAIN/x86_64-linux-android/bin/strip ./snapclient; cp ./snapclient "$JNI_LIBS_DIR/x86_64/libsnapclient.so"; mv ./snapclient "$JNI_LIBS_DIR/x86/libsnapclient.so" export ARCH=arm make clean; make TARGET=ANDROID -j 4; $TOOLCHAIN/arm-linux-androideabi/bin/strip ./snapclient; mv ./snapclient "$JNI_LIBS_DIR/armeabi-v7a/libsnapclient.so" export ARCH=aarch64 make clean; make TARGET=ANDROID -j 4; $TOOLCHAIN/aarch64-linux-android/bin/strip ./snapclient; mv ./snapclient "$JNI_LIBS_DIR/arm64-v8a/libsnapclient.so" snapcast-0.28.0/client/build_android_all.sh000077500000000000000000000002171461051111600206550ustar00rootroot00000000000000#/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.28.0/client/client_connection.cpp000066400000000000000000000261111461051111600210710ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "client_connection.hpp" // local headers #include "common/aixlog.hpp" #include "common/str_compat.hpp" // 3rd party headers #include #include #include // standard headers #include using namespace std; static constexpr auto LOG_TAG = "Connection"; PendingRequest::PendingRequest(const boost::asio::strand& strand, uint16_t reqId, const MessageHandler& handler) : id_(reqId), timer_(strand), strand_(strand), handler_(handler) { } PendingRequest::~PendingRequest() { handler_ = nullptr; timer_.cancel(); } void PendingRequest::setValue(std::unique_ptr value) { boost::asio::post(strand_, [this, self = shared_from_this(), val = std::move(value)]() mutable { timer_.cancel(); if (handler_) handler_({}, std::move(val)); }); } uint16_t PendingRequest::id() const { return id_; } void PendingRequest::startTimer(const chronos::usec& timeout) { timer_.expires_after(timeout); timer_.async_wait( [this, self = shared_from_this()](boost::system::error_code ec) { if (!handler_) return; if (!ec) { // !ec => expired => timeout handler_(boost::asio::error::timed_out, nullptr); handler_ = nullptr; } else if (ec != boost::asio::error::operation_aborted) { // ec != aborted => not cancelled (in setValue) // => should not happen, but who knows => pass the error to the handler handler_(ec, nullptr); } }); } bool PendingRequest::operator<(const PendingRequest& other) const { return (id_ < other.id()); } ClientConnection::ClientConnection(boost::asio::io_context& io_context, const ClientSettings::Server& server) : strand_(boost::asio::make_strand(io_context.get_executor())), resolver_(strand_), socket_(strand_), reqId_(1), server_(server) { base_msg_size_ = base_message_.getSize(); buffer_.resize(base_msg_size_); } ClientConnection::~ClientConnection() { disconnect(); } std::string ClientConnection::getMacAddress() { std::string mac = #ifndef WINDOWS ::getMacAddress(socket_.native_handle()); #else ::getMacAddress(socket_.local_endpoint().address().to_string()); #endif if (mac.empty()) mac = "00:00:00:00:00:00"; LOG(INFO, LOG_TAG) << "My MAC: \"" << mac << "\", socket: " << socket_.native_handle() << "\n"; return mac; } void ClientConnection::connect(const ResultHandler& handler) { tcp::resolver::query query(server_.host, cpt::to_string(server_.port), boost::asio::ip::resolver_query_base::numeric_service); boost::system::error_code ec; LOG(INFO, LOG_TAG) << "Resolving host IP for: " << server_.host << "\n"; auto iterator = resolver_.resolve(query, ec); if (ec) { LOG(ERROR, LOG_TAG) << "Failed to resolve host '" << server_.host << "', error: " << ec.message() << "\n"; handler(ec); return; } for (const auto& iter : iterator) LOG(DEBUG, LOG_TAG) << "Resolved IP: " << iter.endpoint().address().to_string() << "\n"; for (const auto& iter : iterator) { LOG(INFO, LOG_TAG) << "Connecting to " << iter.endpoint() << "\n"; socket_.connect(*iterator, ec); if (!ec || (ec == boost::system::errc::interrupted)) { // We were successful or interrupted, e.g. by sig int break; } } if (ec) LOG(ERROR, LOG_TAG) << "Failed to connect to host '" << server_.host << "', error: " << ec.message() << "\n"; else LOG(NOTICE, LOG_TAG) << "Connected to " << socket_.remote_endpoint().address().to_string() << endl; handler(ec); #if 0 resolver_.async_resolve(query, host_, cpt::to_string(port_), [this, handler](const boost::system::error_code& ec, tcp::resolver::results_type results) { if (ec) { LOG(ERROR, LOG_TAG) << "Failed to resolve host '" << host_ << "', error: " << ec.message() << "\n"; handler(ec); return; } resolver_.cancel(); socket_.async_connect(*results, [this, handler](const boost::system::error_code& ec) { if (ec) { LOG(ERROR, LOG_TAG) << "Failed to connect to host '" << host_ << "', error: " << ec.message() << "\n"; handler(ec); return; } LOG(NOTICE, LOG_TAG) << "Connected to " << socket_.remote_endpoint().address().to_string() << endl; handler(ec); getNextMessage(); }); }); #endif } void ClientConnection::disconnect() { LOG(DEBUG, LOG_TAG) << "Disconnecting\n"; if (!socket_.is_open()) { LOG(DEBUG, LOG_TAG) << "Not connected\n"; return; } boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); if (ec) LOG(ERROR, LOG_TAG) << "Error in socket shutdown: " << ec.message() << endl; socket_.close(ec); if (ec) LOG(ERROR, LOG_TAG) << "Error in socket close: " << ec.message() << endl; boost::asio::post(strand_, [this]() { pendingRequests_.clear(); }); LOG(DEBUG, LOG_TAG) << "Disconnected\n"; } void ClientConnection::sendNext() { auto& message = messages_.front(); static boost::asio::streambuf streambuf; std::ostream stream(&streambuf); tv t; message.msg->sent = t; message.msg->serialize(stream); auto handler = message.handler; boost::asio::async_write(socket_, streambuf, [this, handler](boost::system::error_code ec, std::size_t length) { if (ec) LOG(ERROR, LOG_TAG) << "Failed to send message, error: " << ec.message() << "\n"; else LOG(TRACE, LOG_TAG) << "Wrote " << length << " bytes to socket\n"; messages_.pop_front(); if (handler) handler(ec); if (!messages_.empty()) sendNext(); }); } void ClientConnection::send(const msg::message_ptr& message, const ResultHandler& handler) { boost::asio::post(strand_, [this, message, handler]() { messages_.emplace_back(message, handler); if (messages_.size() > 1) { LOG(DEBUG, LOG_TAG) << "outstanding async_write\n"; return; } sendNext(); }); } void ClientConnection::sendRequest(const msg::message_ptr& message, const chronos::usec& timeout, const MessageHandler& handler) { boost::asio::post(strand_, [this, message, timeout, handler]() { pendingRequests_.erase( std::remove_if(pendingRequests_.begin(), pendingRequests_.end(), [](std::weak_ptr request) { return request.expired(); }), pendingRequests_.end()); unique_ptr response(nullptr); if (++reqId_ >= 10000) reqId_ = 1; message->id = reqId_; auto request = make_shared(strand_, reqId_, handler); pendingRequests_.push_back(request); request->startTimer(timeout); send(message, [handler](const boost::system::error_code& ec) { if (ec) handler(ec, nullptr); }); }); } void ClientConnection::getNextMessage(const MessageHandler& handler) { boost::asio::async_read(socket_, boost::asio::buffer(buffer_, base_msg_size_), [this, handler](boost::system::error_code ec, std::size_t length) mutable { if (ec) { LOG(ERROR, LOG_TAG) << "Error reading message header of length " << length << ": " << ec.message() << "\n"; if (handler) handler(ec, nullptr); return; } base_message_.deserialize(buffer_.data()); tv t; base_message_.received = t; // LOG(TRACE, LOG_TAG) << "getNextMessage: " << base_message_.type << ", size: " << base_message_.size << ", id: " << // base_message_.id << ", refers: " << base_message_.refersTo << "\n"; if (base_message_.type > message_type::kLast) { LOG(ERROR, LOG_TAG) << "unknown message type received: " << base_message_.type << ", size: " << base_message_.size << "\n"; if (handler) handler(boost::asio::error::invalid_argument, nullptr); return; } else if (base_message_.size > msg::max_size) { LOG(ERROR, LOG_TAG) << "received message of type " << base_message_.type << " to large: " << base_message_.size << "\n"; if (handler) handler(boost::asio::error::invalid_argument, nullptr); return; } if (base_message_.size > buffer_.size()) buffer_.resize(base_message_.size); boost::asio::async_read(socket_, boost::asio::buffer(buffer_, base_message_.size), [this, handler](boost::system::error_code ec, std::size_t length) mutable { if (ec) { LOG(ERROR, LOG_TAG) << "Error reading message body of length " << length << ": " << ec.message() << "\n"; if (handler) handler(ec, nullptr); return; } auto response = msg::factory::createMessage(base_message_, buffer_.data()); if (!response) LOG(WARNING, LOG_TAG) << "Failed to deserialize message of type: " << base_message_.type << "\n"; for (auto iter = pendingRequests_.begin(); iter != pendingRequests_.end(); ++iter) { auto request = *iter; if (auto req = request.lock()) { if (req->id() == base_message_.refersTo) { req->setValue(std::move(response)); pendingRequests_.erase(iter); getNextMessage(handler); return; } } } if (handler) handler(ec, std::move(response)); }); }); } snapcast-0.28.0/client/client_connection.hpp000066400000000000000000000120141461051111600210730ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "client_settings.hpp" #include "common/message/factory.hpp" #include "common/message/message.hpp" #include "common/time_defs.hpp" // 3rd party headers #include #include #include #include // standard headers #include #include #include using boost::asio::ip::tcp; class ClientConnection; template using MessageHandler = std::function)>; /// Used to synchronize server requests (wait for server response) class PendingRequest : public std::enable_shared_from_this { public: PendingRequest(const boost::asio::strand& strand, uint16_t reqId, const MessageHandler& handler); virtual ~PendingRequest(); /// Set the response for the pending request and passes it to the handler /// @param value the response message void setValue(std::unique_ptr value); /// @return the id of the request uint16_t id() const; /// Start the timer for the request /// @param timeout the timeout to wait for the reception of the response void startTimer(const chronos::usec& timeout); /// Needed to put the requests in a container bool operator<(const PendingRequest& other) const; private: uint16_t id_; boost::asio::steady_timer timer_; boost::asio::strand strand_; MessageHandler handler_; }; /// 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: using ResultHandler = std::function; /// c'tor ClientConnection(boost::asio::io_context& io_context, const ClientSettings::Server& server); /// d'tor virtual ~ClientConnection(); /// async connect /// @param handler async result handler void connect(const ResultHandler& handler); /// disconnect the socket void disconnect(); /// async send a message /// @param message the message /// @param handler the result handler void send(const msg::message_ptr& message, const ResultHandler& handler); /// Send request to the server and wait for answer /// @param message the message /// @param timeout the send timeout /// @param handler async result handler with the response message or error void sendRequest(const msg::message_ptr& message, const chronos::usec& timeout, const MessageHandler& handler); /// @sa sendRequest with templated response message template void sendRequest(const msg::message_ptr& message, const chronos::usec& timeout, const MessageHandler& handler) { sendRequest(message, timeout, [handler](const boost::system::error_code& ec, std::unique_ptr response) { if (ec) handler(ec, nullptr); else if (auto casted_response = msg::message_cast(std::move(response))) handler(ec, std::move(casted_response)); else handler(boost::system::errc::make_error_code(boost::system::errc::bad_message), nullptr); }); } std::string getMacAddress(); /// async get the next message /// @param handler the next received message or error void getNextMessage(const MessageHandler& handler); protected: void sendNext(); msg::BaseMessage base_message_; std::vector buffer_; size_t base_msg_size_; boost::asio::strand strand_; tcp::resolver resolver_; tcp::socket socket_; std::vector> pendingRequests_; uint16_t reqId_; ClientSettings::Server server_; struct PendingMessage { PendingMessage(const msg::message_ptr& msg, ResultHandler handler) : msg(msg), handler(handler) { } msg::message_ptr msg; ResultHandler handler; }; std::deque messages_; }; snapcast-0.28.0/client/client_settings.hpp000066400000000000000000000034301461051111600205760ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "common/sample_format.hpp" #include "player/pcm_device.hpp" // standard headers #include struct ClientSettings { enum class SharingMode { unspecified, exclusive, shared }; struct Mixer { enum class Mode { hardware, software, script, none }; Mode mode{Mode::software}; std::string parameter{""}; }; struct Server { std::string host{""}; size_t port{1704}; }; struct Player { std::string player_name{""}; std::string parameter{""}; int latency{0}; player::PcmDevice pcm_device; SampleFormat sample_format; SharingMode sharing_mode{SharingMode::unspecified}; Mixer mixer; }; struct Logging { std::string sink{""}; std::string filter{"*:info"}; }; size_t instance{1}; std::string host_id; Server server; Player player; Logging logging; }; snapcast-0.28.0/client/controller.cpp000066400000000000000000000356611461051111600175710ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 NOMINMAX #define NOMINMAX #endif // NOMINMAX // prototype/interface header file #include "controller.hpp" // local headers #include "decoder/null_decoder.hpp" #include "decoder/pcm_decoder.hpp" #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 #ifdef HAS_ALSA #include "player/alsa_player.hpp" #endif #ifdef HAS_PULSE #include "player/pulse_player.hpp" #endif #ifdef HAS_OPENSL #include "player/opensl_player.hpp" #endif #ifdef HAS_OBOE #include "player/oboe_player.hpp" #endif #ifdef HAS_COREAUDIO #include "player/coreaudio_player.hpp" #endif #ifdef HAS_WASAPI #include "player/wasapi_player.hpp" #endif #include "player/file_player.hpp" #include "browseZeroConf/browse_mdns.hpp" #include "common/aixlog.hpp" #include "common/message/client_info.hpp" #include "common/message/hello.hpp" #include "common/message/time.hpp" #include "common/snap_exception.hpp" #include "time_provider.hpp" // standard headers #include #include #include #include using namespace std; using namespace player; static constexpr auto LOG_TAG = "Controller"; static constexpr auto TIME_SYNC_INTERVAL = 1s; Controller::Controller(boost::asio::io_context& io_context, const ClientSettings& settings) //, std::unique_ptr meta) : io_context_(io_context), timer_(io_context), settings_(settings), stream_(nullptr), decoder_(nullptr), player_(nullptr), serverSettings_(nullptr) // meta_(std::move(meta)), { } template std::unique_ptr Controller::createPlayer(ClientSettings::Player& settings, const std::string& player_name) { if (settings.player_name.empty() || settings.player_name == player_name) { settings.player_name = player_name; return make_unique(io_context_, settings, stream_); } return nullptr; } std::vector Controller::getSupportedPlayerNames() { std::vector result; #ifdef HAS_ALSA result.emplace_back(player::ALSA); #endif #ifdef HAS_PULSE result.emplace_back(player::PULSE); #endif #ifdef HAS_OBOE result.emplace_back(player::OBOE); #endif #ifdef HAS_OPENSL result.emplace_back(player::OPENSL); #endif #ifdef HAS_COREAUDIO result.emplace_back(player::COREAUDIO); #endif #ifdef HAS_WASAPI result.emplace_back(player::WASAPI); #endif result.emplace_back(player::FILE); return result; } void Controller::getNextMessage() { clientConnection_->getNextMessage( [this](const boost::system::error_code& ec, std::unique_ptr response) { if (ec) { reconnect(); return; } if (!response) { return getNextMessage(); } if (response->type == message_type::kWireChunk) { if (stream_ && decoder_) { // execute on the io_context to do the (costly) decoding on another thread (if more than one thread is used) // boost::asio::post(io_context_, [this, response = std::move(response)]() mutable { auto pcmChunk = msg::message_cast(std::move(response)); pcmChunk->format = sampleFormat_; // LOG(TRACE, LOG_TAG) << "chunk: " << pcmChunk->payloadSize << ", sampleFormat: " << sampleFormat_.toString() << "\n"; if (decoder_->decode(pcmChunk.get())) { // LOG(TRACE, LOG_TAG) << ", decoded: " << pcmChunk->payloadSize << ", Duration: " << pcmChunk->durationMs() << ", sec: " << // pcmChunk->timestamp.sec << ", usec: " << pcmChunk->timestamp.usec / 1000 << ", type: " << pcmChunk->type << "\n"; stream_->addChunk(std::move(pcmChunk)); } // }); } } else if (response->type == message_type::kServerSettings) { serverSettings_ = msg::message_cast(std::move(response)); LOG(INFO, LOG_TAG) << "ServerSettings - buffer: " << serverSettings_->getBufferMs() << ", latency: " << serverSettings_->getLatency() << ", volume: " << serverSettings_->getVolume() << ", muted: " << serverSettings_->isMuted() << "\n"; if (stream_ && player_) { player_->setVolume({serverSettings_->getVolume() / 100., serverSettings_->isMuted()}); stream_->setBufferLen(std::max(0, serverSettings_->getBufferMs() - serverSettings_->getLatency() - settings_.player.latency)); } } else if (response->type == message_type::kCodecHeader) { headerChunk_ = msg::message_cast(std::move(response)); 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 if (headerChunk_->codec == "null") decoder_ = make_unique(); else throw SnapException("codec not supported: \"" + headerChunk_->codec + "\""); sampleFormat_ = decoder_->setHeader(headerChunk_.get()); LOG(INFO, LOG_TAG) << "Codec: " << headerChunk_->codec << ", sampleformat: " << sampleFormat_.toString() << "\n"; stream_ = make_shared(sampleFormat_, settings_.player.sample_format); stream_->setBufferLen(std::max(0, serverSettings_->getBufferMs() - serverSettings_->getLatency() - settings_.player.latency)); #ifdef HAS_ALSA if (!player_) player_ = createPlayer(settings_.player, player::ALSA); #endif #ifdef HAS_PULSE if (!player_) player_ = createPlayer(settings_.player, player::PULSE); #endif #ifdef HAS_OBOE if (!player_) player_ = createPlayer(settings_.player, player::OBOE); #endif #ifdef HAS_OPENSL if (!player_) player_ = createPlayer(settings_.player, player::OPENSL); #endif #ifdef HAS_COREAUDIO if (!player_) player_ = createPlayer(settings_.player, player::COREAUDIO); #endif #ifdef HAS_WASAPI if (!player_) player_ = createPlayer(settings_.player, player::WASAPI); #endif if (!player_ && (settings_.player.player_name == player::FILE)) player_ = createPlayer(settings_.player, player::FILE); if (!player_) throw SnapException("No audio player support" + (settings_.player.player_name.empty() ? "" : " for: " + settings_.player.player_name)); player_->setVolumeCallback( [this](const Player::Volume& volume) { // Cache the last volume and check if it really changed in the player's volume callback static Player::Volume last_volume{-1, true}; if (volume != last_volume) { last_volume = volume; auto info = std::make_shared(); info->setVolume(static_cast(volume.volume * 100.)); info->setMuted(volume.mute); clientConnection_->send(info, [this](const boost::system::error_code& ec) { if (ec) { LOG(ERROR, LOG_TAG) << "Failed to send client info, error: " << ec.message() << "\n"; reconnect(); return; } }); } }); player_->start(); // Don't change the initial hardware mixer volume on the user's device. // The player class will send the device's volume to the server instead // if (settings_.player.mixer.mode != ClientSettings::Mixer::Mode::hardware) // { player_->setVolume({serverSettings_->getVolume() / 100., serverSettings_->isMuted()}); // } } else { LOG(WARNING, LOG_TAG) << "Unexpected message received, type: " << response->type << "\n"; } getNextMessage(); }); } void Controller::sendTimeSyncMessage(int quick_syncs) { auto timeReq = std::make_shared(); clientConnection_->sendRequest(timeReq, 2s, [this, quick_syncs](const boost::system::error_code& ec, const std::unique_ptr& response) mutable { if (ec) { LOG(ERROR, LOG_TAG) << "Time sync request failed: " << ec.message() << "\n"; reconnect(); return; } else { TimeProvider::getInstance().setDiff(response->latency, response->received - response->sent); } std::chrono::microseconds next = TIME_SYNC_INTERVAL; if (quick_syncs > 0) { if (--quick_syncs == 0) LOG(INFO, LOG_TAG) << "diff to server [ms]: " << static_cast(TimeProvider::getInstance().getDiffToServer().count()) / 1000.f << "\n"; next = 100us; } timer_.expires_after(next); timer_.async_wait( [this, quick_syncs](const boost::system::error_code& ec) { if (!ec) { sendTimeSyncMessage(quick_syncs); } }); }); } void Controller::browseMdns(const MdnsHandler& handler) { #if defined(HAS_AVAHI) || defined(HAS_BONJOUR) try { BrowseZeroConf browser; mDNSResult avahiResult; if (browser.browse("_snapcast._tcp", avahiResult, 1000)) { string host = avahiResult.ip; uint16_t port = avahiResult.port; if (avahiResult.ip_version == IPVersion::IPv6) host += "%" + cpt::to_string(avahiResult.iface_idx); handler({}, host, port); return; } } catch (const std::exception& e) { LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << std::endl; } timer_.expires_after(500ms); timer_.async_wait( [this, handler](const boost::system::error_code& ec) { if (!ec) { browseMdns(handler); } else { handler(ec, "", 0); } }); #else handler(boost::asio::error::operation_not_supported, "", 0); #endif } void Controller::start() { if (settings_.server.host.empty()) { browseMdns( [this](const boost::system::error_code& ec, const std::string& host, uint16_t port) { if (ec) { LOG(ERROR, LOG_TAG) << "Failed to browse MDNS, error: " << ec.message() << "\n"; } else { settings_.server.host = host; settings_.server.port = port; LOG(INFO, LOG_TAG) << "Found server " << settings_.server.host << ":" << settings_.server.port << "\n"; clientConnection_ = make_unique(io_context_, settings_.server); worker(); } }); } else { clientConnection_ = make_unique(io_context_, settings_.server); worker(); } } // void Controller::stop() // { // LOG(DEBUG, LOG_TAG) << "Stopping\n"; // timer_.cancel(); // } void Controller::reconnect() { timer_.cancel(); clientConnection_->disconnect(); player_.reset(); stream_.reset(); decoder_.reset(); timer_.expires_after(1s); timer_.async_wait( [this](const boost::system::error_code& ec) { if (!ec) { worker(); } }); } void Controller::worker() { clientConnection_->connect( [this](const boost::system::error_code& ec) { if (!ec) { // LOG(INFO, LOG_TAG) << "Connected!\n"; string macAddress = clientConnection_->getMacAddress(); if (settings_.host_id.empty()) settings_.host_id = ::getHostId(macAddress); // Say hello to the server auto hello = std::make_shared(macAddress, settings_.host_id, settings_.instance); clientConnection_->sendRequest( hello, 2s, [this](const boost::system::error_code& ec, std::unique_ptr response) mutable { if (ec) { LOG(ERROR, LOG_TAG) << "Failed to send hello request, error: " << ec.message() << "\n"; reconnect(); return; } else { serverSettings_ = std::move(response); LOG(INFO, LOG_TAG) << "ServerSettings - buffer: " << serverSettings_->getBufferMs() << ", latency: " << serverSettings_->getLatency() << ", volume: " << serverSettings_->getVolume() << ", muted: " << serverSettings_->isMuted() << "\n"; } }); // Do initial time sync with the server sendTimeSyncMessage(50); // Start receiver loop getNextMessage(); } else { LOG(ERROR, LOG_TAG) << "Error: " << ec.message() << "\n"; reconnect(); } }); } snapcast-0.28.0/client/controller.hpp000066400000000000000000000047241461051111600175720ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "client_connection.hpp" #include "client_settings.hpp" #include "common/message/server_settings.hpp" #include "decoder/decoder.hpp" #include "player/player.hpp" #include "stream.hpp" // 3rd party headers // standard headers using namespace std::chrono_literals; /// 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: Controller(boost::asio::io_context& io_context, const ClientSettings& settings); //, std::unique_ptr meta); void start(); // void stop(); static std::vector getSupportedPlayerNames(); private: using MdnsHandler = std::function; void worker(); void reconnect(); void browseMdns(const MdnsHandler& handler); template std::unique_ptr createPlayer(ClientSettings::Player& settings, const std::string& player_name); void getNextMessage(); void sendTimeSyncMessage(int quick_syncs); boost::asio::io_context& io_context_; boost::asio::steady_timer timer_; ClientSettings settings_; SampleFormat sampleFormat_; std::unique_ptr clientConnection_; std::shared_ptr stream_; std::unique_ptr decoder_; std::unique_ptr player_; // std::unique_ptr meta_; std::unique_ptr serverSettings_; std::unique_ptr headerChunk_; }; snapcast-0.28.0/client/decoder/000077500000000000000000000000001461051111600162745ustar00rootroot00000000000000snapcast-0.28.0/client/decoder/decoder.hpp000066400000000000000000000023141461051111600204120ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2023 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 . ***/ #pragma once // local headers #include "common/message/codec_header.hpp" #include "common/message/pcm_chunk.hpp" #include "common/sample_format.hpp" // 3rd party headers // standard headers #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 snapcast-0.28.0/client/decoder/flac_decoder.cpp000066400000000000000000000211431461051111600213730ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "flac_decoder.hpp" // local headers #include "common/aixlog.hpp" #include "common/endian.hpp" #include "common/snap_exception.hpp" // standard headers #include #include using namespace std; static constexpr auto LOG_TAG = "FlacDecoder"; 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 = static_cast(realloc(flacChunk->payload, chunk->payloadSize)); memcpy(flacChunk->payload, chunk->payload, chunk->payloadSize); flacChunk->payloadSize = chunk->payloadSize; pcmChunk->payload = static_cast(realloc(pcmChunk->payload, 0)); pcmChunk->payloadSize = 0; while (flacChunk->payloadSize > 0) { if (FLAC__stream_decoder_process_single(decoder) == 0) { return false; } if (lastError_) { LOG(ERROR, LOG_TAG) << "FLAC decode error: " << FLAC__StreamDecoderErrorStatusString[*lastError_] << "\n"; lastError_ = nullptr; return false; } } if ((cacheInfo_.cachedBlocks_ > 0) && (cacheInfo_.sampleRate_ != 0)) { double diffMs = static_cast(cacheInfo_.cachedBlocks_) / (static_cast(cacheInfo_.sampleRate_) / 1000.); auto us = static_cast(diffMs * 1000.); tv diff(static_cast(us / 1000000), static_cast(us % 1000000)); LOG(TRACE, LOG_TAG) << "Cached: " << cacheInfo_.cachedBlocks_ << ", " << diffMs << "ms, " << diff.sec << "s, " << diff.usec << "us\n"; chunk->timestamp = chunk->timestamp - diff; } 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])); 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 - static_cast(*bytes); flacChunk->payload = static_cast(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(); auto* flacDecoder = static_cast(client_data); if (flacDecoder->cacheInfo_.isCachedChunk_) flacDecoder->cacheInfo_.cachedBlocks_ += frame->header.blocksize; pcmChunk->payload = static_cast(realloc(pcmChunk->payload, pcmChunk->payloadSize + bytes)); for (size_t channel = 0; channel < sampleFormat.channels(); ++channel) { if (buffer[channel] == nullptr) { LOG(ERROR, LOG_TAG) << "ERROR: buffer[" << channel << "] is NULL\n"; return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; } if (sampleFormat.sampleSize() == 1) { auto* chunkBuffer = reinterpret_cast(pcmChunk->payload + pcmChunk->payloadSize); for (size_t i = 0; i < frame->header.blocksize; i++) chunkBuffer[sampleFormat.channels() * i + channel] = static_cast(buffer[channel][i]); } else if (sampleFormat.sampleSize() == 2) { auto* chunkBuffer = reinterpret_cast(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) { auto* chunkBuffer = reinterpret_cast(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 += static_cast(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, static_cast(metadata->data.stream_info.bits_per_sample), static_cast(metadata->data.stream_info.channels)); } } void error_callback(const FLAC__StreamDecoder* /*decoder*/, FLAC__StreamDecoderErrorStatus status, void* client_data) { LOG(ERROR, LOG_TAG) << "Got error callback: " << FLAC__StreamDecoderErrorStatusString[status] << "\n"; static_cast(client_data)->lastError_ = std::make_unique(status); } } // namespace callback } // namespace decoder snapcast-0.28.0/client/decoder/flac_decoder.hpp000066400000000000000000000027131461051111600214020ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "decoder.hpp" // 3rd party headers #include // standard headers #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 snapcast-0.28.0/client/decoder/null_decoder.cpp000066400000000000000000000021741461051111600214430ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "null_decoder.hpp" // local headers // 3rd party headers // standard headers namespace decoder { NullDecoder::NullDecoder() : Decoder() { } bool NullDecoder::decode(msg::PcmChunk* /*chunk*/) { return true; } SampleFormat NullDecoder::setHeader(msg::CodecHeader* chunk) { std::ignore = chunk; return {48000, 16, 2}; } } // namespace decoder snapcast-0.28.0/client/decoder/null_decoder.hpp000066400000000000000000000017731461051111600214540ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2023 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 . ***/ #pragma once // local headers #include "decoder.hpp" namespace decoder { class NullDecoder : public Decoder { public: NullDecoder(); bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; }; } // namespace decoder snapcast-0.28.0/client/decoder/ogg_decoder.cpp000066400000000000000000000214551461051111600212500ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "ogg_decoder.hpp" // local headers #include "common/aixlog.hpp" #include "common/endian.hpp" #include "common/snap_exception.hpp" // 3rd party headers // standard headers #ifndef HAS_TREMOR #include // floor #endif #include #include using namespace std; static constexpr auto LOG_TAG = "OggDecoder"; 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, LOG_TAG) << "Corrupt or missing data in bitstream; continuing...\n"; continue; } ogg_stream_pagein(&os, &og); /* can safely ignore errors at this point */ while (true) { 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) { uint32_t bytes = sampleFormat_.sampleSize() * vi.channels * samples; chunk->payload = static_cast(realloc(chunk->payload, chunk->payloadSize + bytes)); for (int channel = 0; channel < vi.channels; ++channel) { if (sampleFormat_.sampleSize() == 1) { auto* chunkBuffer = reinterpret_cast(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], INT8_MIN, INT8_MAX); #else val = clip(floor(pcm[channel][i] * 127.f + .5f), INT8_MIN, INT8_MAX); #endif } } else if (sampleFormat_.sampleSize() == 2) { auto* chunkBuffer = reinterpret_cast(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, INT16_MIN, INT16_MAX)); #else val = SWAP_16(clip(floor(pcm[channel][i] * 32767.f + .5f), INT16_MIN, INT16_MAX)); #endif } } else if (sampleFormat_.sampleSize() == 4) { auto* chunkBuffer = reinterpret_cast(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, INT32_MIN, INT32_MAX)); #else val = SWAP_32(clip(floor(pcm[channel][i] * 2147483647.f + .5f), INT32_MIN, INT32_MAX)); #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, static_cast(vi.channels)); /* Throw the comments plus a few lines about the bitstream we're decoding */ char** ptr = vc.user_comments; while (*ptr != nullptr) { std::string comment(*ptr); if (comment.find("SAMPLE_FORMAT=") == 0) sampleFormat_.setFormat(comment.substr(comment.find('=') + 1)); LOG(INFO, LOG_TAG) << "comment: " << comment << "\n"; ; ++ptr; } LOG(INFO, LOG_TAG) << "Encoded by: " << vc.vendor << "\n"; return sampleFormat_; } } // namespace decoder snapcast-0.28.0/client/decoder/ogg_decoder.hpp000066400000000000000000000042361461051111600212530ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "decoder.hpp" // 3rd party headers #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 IN_TYPE& value, const T& lower, const T& upper) const { auto val = static_cast(value); if (val > upper) return upper; if (val < lower) return lower; return static_cast(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 snapcast-0.28.0/client/decoder/opus_decoder.cpp000066400000000000000000000103771461051111600214630ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2015 Hannes Ellinger Copyright (C) 2016-2024 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 . ***/ // prototype/interface header file #include "opus_decoder.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.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; static constexpr auto LOG_TAG = "OpusDecoder"; OpusDecoder::OpusDecoder() : Decoder(), dec_(nullptr) { pcm_.resize(120); } OpusDecoder::~OpusDecoder() { if (dec_ != nullptr) opus_decoder_destroy(dec_); } bool OpusDecoder::decode(msg::PcmChunk* chunk) { int decoded_frames = 0; while ((decoded_frames = opus_decode(dec_, reinterpret_cast(chunk->payload), chunk->payloadSize, pcm_.data(), static_cast(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(DEBUG, LOG_TAG) << "OPUS encoding buffer too small, resizing to " << pcm_.size() / sample_format_.channels() << " samples per channel\n"; } else break; } if (decoded_frames < 0) { LOG(ERROR, LOG_TAG) << "Failed to decode chunk: " << opus_strerror(decoded_frames) << ", IN size: " << chunk->payloadSize << ", OUT size: " << pcm_.size() << '\n'; return false; } else { LOG(TRACE, LOG_TAG) << "Decode chunk: " << decoded_frames << " frames, size: " << chunk->payloadSize << " bytes, decoded: " << decoded_frames * sample_format_.frameSize() << " bytes\n"; // copy encoded data to chunk chunk->payloadSize = decoded_frames * sample_format_.frameSize(); // decoded_frames * sample_format_.channels() * sizeof(opus_int16); chunk->payload = static_cast(realloc(chunk->payload, chunk->payloadSize)); memcpy(chunk->payload, reinterpret_cast(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(rate)); 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, LOG_TAG) << "Opus sampleformat: " << sample_format_.toString() << "\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.28.0/client/decoder/opus_decoder.hpp000066400000000000000000000024551461051111600214660ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2015 Hannes Ellinger Copyright (C) 2016-2024 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 . ***/ #pragma once // local headers #include "decoder/decoder.hpp" // 3rd party headers #include // standard headers #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.28.0/client/decoder/pcm_decoder.cpp000066400000000000000000000070721461051111600212520ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "pcm_decoder.hpp" // local headers #include "common/endian.hpp" #include "common/snap_exception.hpp" namespace decoder { static constexpr auto ID_RIFF = 0x46464952; static constexpr auto ID_WAVE = 0x45564157; static constexpr auto ID_FMT = 0x20746d66; static constexpr auto 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.28.0/client/decoder/pcm_decoder.hpp000066400000000000000000000017711461051111600212570ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #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 snapcast-0.28.0/client/double_buffer.hpp000066400000000000000000000073221461051111600202070ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // standard headers #include #include #include #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(uint16_t 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 { uint16_t low = static_cast(tmpBuffer.size()) / 2; uint16_t high = low; low -= mean / 2; high += mean / 2; T result((T)0); for (uint16_t 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() - 1) * ((float)percentile / (float)100))]; } template std::array percentiles(std::array percentiles) const { std::array result; result.fill(0); if (buffer.empty()) return result; std::deque tmpBuffer(buffer.begin(), buffer.end()); std::sort(tmpBuffer.begin(), tmpBuffer.end()); for (std::size_t i = 0; i < Size; ++i) result[i] = tmpBuffer[(size_t)((tmpBuffer.size() - 1) * ((float)percentiles[i] / (float)100))]; return result; } 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.empty(); } void setSize(size_t size) { bufferSize = size; } const std::deque& getBuffer() const { return buffer; } private: size_t bufferSize; std::deque buffer; }; snapcast-0.28.0/client/etc/000077500000000000000000000000001461051111600154425ustar00rootroot00000000000000snapcast-0.28.0/client/etc/snapcast.svg000066400000000000000000000172351461051111600200070ustar00rootroot00000000000000 image/svg+xml snapcast-0.28.0/client/etc/snapclient.plist000066400000000000000000000007501461051111600206610ustar00rootroot00000000000000 Label de.badaix.snapcast.snapclient ProgramArguments /usr/local/bin/snapclient --logsink=system RunAtLoad KeepAlive snapcast-0.28.0/client/metadata.hpp000066400000000000000000000040221461051111600171560ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "common/json.hpp" // standard headers #include // Prefix used in output #define METADATA std::string("metadata") /* * Implement a generic metadata output handler */ using json = nlohmann::json; /* * Base class, prints to stdout */ class MetadataAdapter { public: MetadataAdapter() { reset(); } virtual ~MetadataAdapter() = default; void reset() { msg_ = json{}; } std::string serialize() { return METADATA + ":" + msg_.dump(); } void tag(const std::string& name, const std::string& value) { msg_[name] = value; } std::string operator[](const std::string& key) { try { return msg_[key]; } catch (std::domain_error&) { return std::string(); } } virtual int push() { std::cout << serialize() << "\n"; return 0; } int push(const json& jtag) { msg_ = jtag; return push(); } protected: json msg_; }; /* * Send metadata to stderr as json */ class MetaStderrAdapter : public MetadataAdapter { public: using MetadataAdapter::push; int push() override { std::cerr << serialize() << "\n"; return 0; } }; snapcast-0.28.0/client/player/000077500000000000000000000000001461051111600161635ustar00rootroot00000000000000snapcast-0.28.0/client/player/alsa_player.cpp000066400000000000000000000644601461051111600211750ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "alsa_player.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "common/utils/logging.hpp" #include "common/utils/string_utils.hpp" // 3rd party headers // standard headers #include using namespace std::chrono_literals; using namespace std; namespace player { static constexpr std::chrono::milliseconds BUFFER_TIME = 80ms; static constexpr int PERIODS = 4; static constexpr int MIN_PERIODS = 3; #define exp10(x) (exp((x)*log(10))) static constexpr auto LOG_TAG = "Alsa"; static constexpr auto DEFAULT_MIXER = "PCM"; AlsaPlayer::AlsaPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : Player(io_context, settings, stream), handle_(nullptr), ctl_(nullptr), mixer_(nullptr), elem_(nullptr), sd_(io_context), timer_(io_context) { if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware) { string tmp; if (settings_.mixer.parameter.empty()) mixer_name_ = DEFAULT_MIXER; else mixer_name_ = utils::string::split_left(settings_.mixer.parameter, ':', tmp); string card; // default:CARD=ALSA[,DEV=x] => default mixer_device_ = utils::string::split_left(settings_.pcm_device.name, ':', card); if (!card.empty()) { auto pos = card.find("CARD="); if (pos != string::npos) { card = card.substr(pos + 5); card = utils::string::split_left(card, ',', tmp); int card_idx = snd_card_get_index(card.c_str()); if ((card_idx >= 0) && (card_idx < 32)) mixer_device_ = "hw:" + std::to_string(card_idx); } } LOG(DEBUG, LOG_TAG) << "Mixer: " << mixer_name_ << ", device: " << mixer_device_ << "\n"; } auto params = utils::string::split_pairs(settings.parameter, ',', '='); if (params.find("buffer_time") != params.end()) buffer_time_ = std::chrono::milliseconds(std::max(cpt::stoi(params["buffer_time"]), 10)); if (params.find("fragments") != params.end()) periods_ = std::max(cpt::stoi(params["fragments"]), 2); LOG(INFO, LOG_TAG) << "Using " << (buffer_time_.has_value() ? "configured" : "default") << " buffer_time: " << buffer_time_.value_or(BUFFER_TIME).count() / 1000 << " ms, " << (periods_.has_value() ? "configured" : "default") << " fragments: " << periods_.value_or(PERIODS) << "\n"; } void AlsaPlayer::setHardwareVolume(const Volume& volume) { std::lock_guard lock(mutex_); if (elem_ == nullptr) return; last_change_ = std::chrono::steady_clock::now(); try { int val = volume.mute ? 0 : 1; int err = snd_mixer_selem_set_playback_switch_all(elem_, val); if (err < 0) LOG(ERROR, LOG_TAG) << "Failed to mute, error: " << snd_strerror(err) << "\n"; long minv, maxv; if ((err = snd_mixer_selem_get_playback_dB_range(elem_, &minv, &maxv)) == 0) { double min_norm = exp10((minv - maxv) / 6000.0); double vol = volume.volume * (1 - min_norm) + min_norm; double mixer_volume = 6000.0 * log10(vol) + maxv; LOG(DEBUG, LOG_TAG) << "Mixer playback dB range [" << minv << ", " << maxv << "], volume: " << vol << ", mixer volume: " << mixer_volume << "\n"; if ((err = snd_mixer_selem_set_playback_dB_all(elem_, mixer_volume, 0)) < 0) throw SnapException(std::string("Failed to set playback volume, error: ") + snd_strerror(err)); } else { if ((err = snd_mixer_selem_get_playback_volume_range(elem_, &minv, &maxv)) < 0) throw SnapException(std::string("Failed to get playback volume range, error: ") + snd_strerror(err)); auto mixer_volume = volume.volume * (maxv - minv) + minv; LOG(DEBUG, LOG_TAG) << "Mixer playback volume range [" << minv << ", " << maxv << "], volume: " << volume.volume << ", mixer volume: " << mixer_volume << "\n"; if ((err = snd_mixer_selem_set_playback_volume_all(elem_, mixer_volume)) < 0) throw SnapException(std::string("Failed to set playback volume, error: ") + snd_strerror(err)); } } catch (const std::exception& e) { LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << "\n"; uninitMixer(); } } bool AlsaPlayer::getHardwareVolume(Volume& volume) { try { std::lock_guard lock(mutex_); if (elem_ == nullptr) throw SnapException("Mixer not initialized"); long vol; int err = 0; while (snd_mixer_handle_events(mixer_) > 0) this_thread::sleep_for(1us); long minv, maxv; if ((err = snd_mixer_selem_get_playback_dB_range(elem_, &minv, &maxv)) == 0) { if ((err = snd_mixer_selem_get_playback_dB(elem_, SND_MIXER_SCHN_MONO, &vol)) < 0) throw SnapException(std::string("Failed to get playback volume, error: ") + snd_strerror(err)); volume.volume = pow(10, (vol - maxv) / 6000.0); if (minv != SND_CTL_TLV_DB_GAIN_MUTE) { double min_norm = pow(10, (minv - maxv) / 6000.0); volume.volume = (volume.volume - min_norm) / (1 - min_norm); } } else { if ((err = snd_mixer_selem_get_playback_volume_range(elem_, &minv, &maxv)) < 0) throw SnapException(std::string("Failed to get playback volume range, error: ") + snd_strerror(err)); if ((err = snd_mixer_selem_get_playback_volume(elem_, SND_MIXER_SCHN_MONO, &vol)) < 0) throw SnapException(std::string("Failed to get playback volume, error: ") + snd_strerror(err)); vol -= minv; maxv = maxv - minv; volume.volume = static_cast(vol) / static_cast(maxv); } int val; if ((err = snd_mixer_selem_get_playback_switch(elem_, SND_MIXER_SCHN_MONO, &val)) < 0) throw SnapException(std::string("Failed to get mute state, error: ") + snd_strerror(err)); volume.mute = (val == 0); LOG(DEBUG, LOG_TAG) << "Get volume, mixer volume range [" << minv << ", " << maxv << "], volume: " << volume.volume << ", muted: " << volume.mute << "\n"; snd_mixer_handle_events(mixer_); return true; } catch (const std::exception& e) { LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << "\n"; return false; } } void AlsaPlayer::waitForEvent() { sd_.async_wait(boost::asio::posix::stream_descriptor::wait_read, [this](const boost::system::error_code& ec) { if (ec) { // TODO: fd is "Bad" after unplugging/plugging USB DAC, i.e. after init/uninit/init cycle LOG(DEBUG, LOG_TAG) << "waitForEvent error: " << ec.message() << "\n"; return; } std::lock_guard lock(mutex_); if (ctl_ == nullptr) return; unsigned short revents; snd_ctl_poll_descriptors_revents(ctl_, fd_.get(), 1, &revents); if (((revents & POLLIN) != 0) || (revents == 0)) { snd_ctl_event_t* event; snd_ctl_event_alloca(&event); if (((snd_ctl_read(ctl_, event) >= 0) && (snd_ctl_event_get_type(event) == SND_CTL_EVENT_ELEM)) || (revents == 0)) { auto now = std::chrono::steady_clock::now(); if (now - last_change_ < 1s) { LOG(DEBUG, LOG_TAG) << "Last volume change by server: " << std::chrono::duration_cast(now - last_change_).count() << " ms => ignoring volume change\n"; waitForEvent(); return; } // Sometimes the old volume is reported by getHardwareVolume after this event has been raised. // As workaround we defer getting the volume by 20ms. timer_.cancel(); timer_.expires_after(20ms); timer_.async_wait( [this](const boost::system::error_code& ec) { if (!ec) { if (getHardwareVolume(volume_)) { LOG(DEBUG, LOG_TAG) << "Volume changed: " << volume_.volume << ", muted: " << volume_.mute << "\n"; notifyVolumeChange(volume_); } } }); } } waitForEvent(); }); } void AlsaPlayer::initMixer() { if (settings_.mixer.mode != ClientSettings::Mixer::Mode::hardware) return; LOG(DEBUG, LOG_TAG) << "initMixer\n"; std::lock_guard lock(mutex_); int err; if ((err = snd_ctl_open(&ctl_, mixer_device_.c_str(), SND_CTL_READONLY)) < 0) throw SnapException("Can't open control for " + mixer_device_ + ", error: " + snd_strerror(err)); if ((err = snd_ctl_subscribe_events(ctl_, 1)) < 0) throw SnapException("Can't subscribe for events for " + mixer_device_ + ", error: " + snd_strerror(err)); fd_ = std::unique_ptr>(new pollfd(), [](pollfd* p) { close(p->fd); delete p; }); err = snd_ctl_poll_descriptors(ctl_, fd_.get(), 1); LOG(DEBUG, LOG_TAG) << "Filled " << err << " poll descriptors, poll descriptor count: " << snd_ctl_poll_descriptors_count(ctl_) << ", fd: " << fd_->fd << "\n"; snd_mixer_selem_id_t* sid; snd_mixer_selem_id_alloca(&sid); int mix_index = 0; // sets simple-mixer index and name snd_mixer_selem_id_set_index(sid, mix_index); snd_mixer_selem_id_set_name(sid, mixer_name_.c_str()); if ((err = snd_mixer_open(&mixer_, 0)) < 0) throw SnapException(std::string("Failed to open mixer, error: ") + snd_strerror(err)); if ((err = snd_mixer_attach(mixer_, mixer_device_.c_str())) < 0) throw SnapException("Failed to attach mixer to " + mixer_device_ + ", error: " + snd_strerror(err)); if ((err = snd_mixer_selem_register(mixer_, nullptr, nullptr)) < 0) throw SnapException(std::string("Failed to register selem, error: ") + snd_strerror(err)); if ((err = snd_mixer_load(mixer_)) < 0) throw SnapException(std::string("Failed to load mixer, error: ") + snd_strerror(err)); elem_ = snd_mixer_find_selem(mixer_, sid); if (elem_ == nullptr) throw SnapException("Failed to find mixer: " + mixer_name_); sd_ = boost::asio::posix::stream_descriptor(io_context_, fd_->fd); waitForEvent(); } void AlsaPlayer::initAlsa() { std::lock_guard lock(mutex_); const SampleFormat& format = stream_->getFormat(); uint32_t rate = format.rate(); int channels = format.channels(); int err; // Open the PCM device in playback mode if ((err = snd_pcm_open(&handle_, settings_.pcm_device.name.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) throw SnapException("Can't open " + settings_.pcm_device.name + ", error: " + snd_strerror(err), err); // struct snd_pcm_playback_info_t pinfo; // if ((pcm = snd_pcm_playback_info( pcm_handle, &pinfo)) < 0) // fprintf(stderr, "Error: playback info error: %s\n", snd_strerror(err)); // printf("buffer: '%d'\n", pinfo.buffer_size); // Allocate parameters object and fill it with default values snd_pcm_hw_params_t* params; snd_pcm_hw_params_alloca(¶ms); if ((err = snd_pcm_hw_params_any(handle_, params)) < 0) throw SnapException("Can't fill params: " + string(snd_strerror(err))); snd_output_t* output; if (snd_output_buffer_open(&output) == 0) { if (snd_pcm_hw_params_dump(params, output) == 0) { char* str; size_t len = snd_output_buffer_string(output, &str); LOG(DEBUG, LOG_TAG) << std::string(str, len) << "\n"; } snd_output_close(output); } // Set parameters if ((err = snd_pcm_hw_params_set_access(handle_, params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) throw SnapException("Can't set interleaved mode: " + string(snd_strerror(err))); snd_pcm_format_t snd_pcm_format; if (format.bits() == 8) snd_pcm_format = SND_PCM_FORMAT_S8; else if (format.bits() == 16) snd_pcm_format = SND_PCM_FORMAT_S16_LE; else if ((format.bits() == 24) && (format.sampleSize() == 4)) snd_pcm_format = SND_PCM_FORMAT_S24_LE; else if (format.bits() == 32) snd_pcm_format = SND_PCM_FORMAT_S32_LE; else throw SnapException("Unsupported sample format: " + cpt::to_string(format.bits())); err = snd_pcm_hw_params_set_format(handle_, params, snd_pcm_format); if (err == -EINVAL) { if (snd_pcm_format == SND_PCM_FORMAT_S24_LE) { snd_pcm_format = SND_PCM_FORMAT_S32_LE; volCorrection_ = 256; } if (snd_pcm_format == SND_PCM_FORMAT_S8) { snd_pcm_format = SND_PCM_FORMAT_U8; } } err = snd_pcm_hw_params_set_format(handle_, params, snd_pcm_format); if (err < 0) { stringstream ss; ss << "Can't set format: " << string(snd_strerror(err)) << ", supported: "; for (int format = 0; format <= static_cast(SND_PCM_FORMAT_LAST); format++) { auto snd_pcm_format = static_cast(format); if (snd_pcm_hw_params_test_format(handle_, params, snd_pcm_format) == 0) ss << snd_pcm_format_name(snd_pcm_format) << " "; } throw SnapException(ss.str()); } if ((err = snd_pcm_hw_params_set_channels(handle_, params, channels)) < 0) throw SnapException("Can't set channel count: " + string(snd_strerror(err))); if ((err = snd_pcm_hw_params_set_rate_near(handle_, params, &rate, nullptr)) < 0) throw SnapException("Can't set rate: " + string(snd_strerror(err))); if (rate != format.rate()) LOG(WARNING, LOG_TAG) << "Could not set sample rate to " << format.rate() << " Hz, using: " << rate << " Hz\n"; uint32_t period_time = buffer_time_.value_or(BUFFER_TIME).count() / periods_.value_or(PERIODS); uint32_t max_period_time = period_time; if ((err = snd_pcm_hw_params_get_period_time_max(params, &max_period_time, nullptr)) < 0) { LOG(ERROR, LOG_TAG) << "Can't get max period time: " << snd_strerror(err) << "\n"; } else { if (period_time > max_period_time) { LOG(INFO, LOG_TAG) << "Period time too large, changing from " << period_time << " to " << max_period_time << "\n"; period_time = max_period_time; } } uint32_t min_period_time = period_time; if ((err = snd_pcm_hw_params_get_period_time_min(params, &min_period_time, nullptr)) < 0) { LOG(ERROR, LOG_TAG) << "Can't get min period time: " << snd_strerror(err) << "\n"; } else { if (period_time < min_period_time) { LOG(INFO, LOG_TAG) << "Period time too small, changing from " << period_time << " to " << min_period_time << "\n"; period_time = min_period_time; } } if ((err = snd_pcm_hw_params_set_period_time_near(handle_, params, &period_time, nullptr)) < 0) throw SnapException("Can't set period time: " + string(snd_strerror(err))); uint32_t buffer_time = buffer_time_.value_or(BUFFER_TIME).count(); uint32_t periods = periods_.value_or(MIN_PERIODS); if (buffer_time < period_time * periods) { LOG(INFO, LOG_TAG) << "Buffer time smaller than " << periods << " * periods: " << buffer_time << " us < " << period_time * periods << " us, raising buffer time\n"; buffer_time = period_time * periods; } if ((err = snd_pcm_hw_params_set_buffer_time_near(handle_, params, &buffer_time, nullptr)) < 0) throw SnapException("Can't set buffer time to " + cpt::to_string(buffer_time) + " us : " + string(snd_strerror(err))); // unsigned int periods = periods_; // if ((err = snd_pcm_hw_params_set_periods_near(handle_, params, &periods, 0)) < 0) // throw SnapException("Can't set periods: " + string(snd_strerror(err))); // Write parameters if ((err = snd_pcm_hw_params(handle_, params)) < 0) throw SnapException("Can't set hardware parameters: " + string(snd_strerror(err))); // Resume information // uint32_t periods; if (snd_pcm_hw_params_get_periods(params, &periods, nullptr) < 0) periods = round(static_cast(buffer_time) / static_cast(period_time)); snd_pcm_hw_params_get_period_size(params, &frames_, nullptr); LOG(INFO, LOG_TAG) << "PCM name: " << snd_pcm_name(handle_) << ", sample rate: " << rate << " Hz, channels: " << channels << ", buffer time: " << buffer_time << " us, periods: " << periods << ", period time: " << period_time << " us, period frames: " << frames_ << "\n"; // Allocate buffer to hold single period snd_pcm_sw_params_t* swparams; snd_pcm_sw_params_alloca(&swparams); snd_pcm_sw_params_current(handle_, swparams); snd_pcm_sw_params_set_avail_min(handle_, swparams, frames_); snd_pcm_sw_params_set_start_threshold(handle_, swparams, frames_); // snd_pcm_sw_params_set_stop_threshold(pcm_handle, swparams, frames_); snd_pcm_sw_params(handle_, swparams); if (snd_pcm_state(handle_) == SND_PCM_STATE_PREPARED) { if ((err = snd_pcm_start(handle_)) < 0) LOG(DEBUG, LOG_TAG) << "Failed to start PCM: " << snd_strerror(err) << "\n"; } if (ctl_ == nullptr) initMixer(); } void AlsaPlayer::uninitAlsa(bool uninit_mixer) { std::lock_guard lock(mutex_); if (uninit_mixer) uninitMixer(); if (handle_ != nullptr) { snd_pcm_drop(handle_); snd_pcm_close(handle_); handle_ = nullptr; } } void AlsaPlayer::uninitMixer() { if (settings_.mixer.mode != ClientSettings::Mixer::Mode::hardware) return; LOG(DEBUG, LOG_TAG) << "uninitMixer\n"; std::lock_guard lock(mutex_); if (sd_.is_open()) { boost::system::error_code ec; sd_.cancel(ec); } if (ctl_ != nullptr) { snd_ctl_close(ctl_); ctl_ = nullptr; } if (mixer_ != nullptr) { snd_mixer_close(mixer_); mixer_ = nullptr; } fd_ = nullptr; elem_ = nullptr; } void AlsaPlayer::start() { try { initAlsa(); } catch (const SnapException& e) { LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << ", code: " << e.code() << "\n"; // Accept "Device or ressource busy", the worker loop will retry if (e.code() != -EBUSY) throw; } Player::start(); } AlsaPlayer::~AlsaPlayer() { stop(); } void AlsaPlayer::stop() { Player::stop(); uninitAlsa(true); } bool AlsaPlayer::needsThread() const { return true; } bool AlsaPlayer::getAvailDelay(snd_pcm_sframes_t& avail, snd_pcm_sframes_t& delay) { int result = snd_pcm_avail_delay(handle_, &avail, &delay); if (result < 0) { LOG(WARNING, LOG_TAG) << "snd_pcm_avail_delay failed: " << snd_strerror(result) << " (" << result << "), avail: " << avail << ", delay: " << delay << ", using snd_pcm_avail amd snd_pcm_delay.\n"; this_thread::sleep_for(1ms); avail = snd_pcm_avail(handle_); result = snd_pcm_delay(handle_, &delay); if ((result < 0) || (delay < 0)) { LOG(WARNING, LOG_TAG) << "snd_pcm_delay failed: " << snd_strerror(result) << " (" << result << "), avail: " << avail << ", delay: " << delay << "\n"; return false; } // LOG(DEBUG, LOG_TAG) << "snd_pcm_delay: " << delay << ", snd_pcm_avail: " << avail << "\n"; } if (avail < 0) { LOG(DEBUG, LOG_TAG) << "snd_pcm_avail failed: " << snd_strerror(avail) << " (" << avail << "), using " << frames_ << "\n"; avail = frames_; } return true; } void AlsaPlayer::worker() { snd_pcm_sframes_t pcm; snd_pcm_sframes_t framesDelay; snd_pcm_sframes_t framesAvail; long lastChunkTick = chronos::getTickCount(); const SampleFormat& format = stream_->getFormat(); while (active_) { if (handle_ == nullptr) { try { initAlsa(); // set the hardware volume. It might have changed when we were not initialized if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware) setHardwareVolume(volume_); } catch (const std::exception& e) { LOG(ERROR, LOG_TAG) << "Exception in initAlsa: " << e.what() << endl; chronos::sleep(100); } if (handle_ == nullptr) continue; } int wait_result = snd_pcm_wait(handle_, 100); if (wait_result == -EPIPE) { LOG(ERROR, LOG_TAG) << "XRUN while waiting for PCM: " << snd_strerror(wait_result) << "\n"; snd_pcm_prepare(handle_); } else if (wait_result < 0) { LOG(ERROR, LOG_TAG) << "ERROR. Can't wait for PCM to become ready: " << snd_strerror(wait_result) << "\n"; uninitAlsa(true); continue; } else if (wait_result == 0) { continue; } if (!getAvailDelay(framesAvail, framesDelay)) { this_thread::sleep_for(10ms); snd_pcm_prepare(handle_); continue; } // if (framesAvail < static_cast(frames_)) // { // this_thread::sleep_for(5ms); // continue; // } if (framesAvail == 0) { auto frame_time = std::chrono::microseconds(static_cast(frames_ / format.usRate())); std::chrono::microseconds wait = std::min(frame_time / 2, std::chrono::microseconds(10ms)); LOG(DEBUG, LOG_TAG) << "No frames available, waiting for " << wait.count() << " us\n"; this_thread::sleep_for(wait); continue; } // LOG(TRACE, LOG_TAG) << "res: " << result << ", framesAvail: " << framesAvail << ", delay: " << framesDelay << ", frames: " << frames_ << "\n"; chronos::usec delay(static_cast(1000 * static_cast(framesDelay) / format.msRate())); // LOG(TRACE, LOG_TAG) << "delay: " << framesDelay << ", delay[ms]: " << delay.count() / 1000 << ", avail: " << framesAvail << "\n"; if (buffer_.size() < static_cast(framesAvail * format.frameSize())) { LOG(DEBUG, LOG_TAG) << "Resizing buffer from " << buffer_.size() << " to " << framesAvail * format.frameSize() << "\n"; buffer_.resize(framesAvail * format.frameSize()); } if (stream_->getPlayerChunk(buffer_.data(), delay, framesAvail)) { lastChunkTick = chronos::getTickCount(); adjustVolume(buffer_.data(), framesAvail); if ((pcm = snd_pcm_writei(handle_, buffer_.data(), framesAvail)) == -EPIPE) { LOG(ERROR, LOG_TAG) << "XRUN while writing to PCM: " << snd_strerror(pcm) << "\n"; snd_pcm_prepare(handle_); } else if (pcm < 0) { LOG(ERROR, LOG_TAG) << "ERROR. Can't write to PCM device: " << snd_strerror(pcm) << "\n"; uninitAlsa(true); } } else { LOG(INFO, LOG_TAG) << "Failed to get chunk\n"; while (active_ && !stream_->waitForChunk(100ms)) { // Log "Waiting for chunk" only every second second static utils::logging::TimeConditional cond(2s); LOG(DEBUG, LOG_TAG) << cond << "Waiting for chunk\n"; if ((handle_ != nullptr) && (chronos::getTickCount() - lastChunkTick > 5000)) { LOG(NOTICE, LOG_TAG) << "No chunk received for 5000ms. Closing ALSA.\n"; uninitAlsa(false); stream_->clearChunks(); } } } } } vector AlsaPlayer::pcm_list() { void **hints, **n; char *name, *descr, *io; vector result; PcmDevice pcmDevice; if (snd_device_name_hint(-1, "pcm", &hints) < 0) return result; n = hints; size_t idx(0); while (*n != nullptr) { name = snd_device_name_get_hint(*n, "NAME"); descr = snd_device_name_get_hint(*n, "DESC"); io = snd_device_name_get_hint(*n, "IOID"); if (io != nullptr && strcmp(io, "Output") != 0) goto __end; pcmDevice.name = name; if (descr == nullptr) { pcmDevice.description = ""; } else { pcmDevice.description = descr; } pcmDevice.idx = idx++; result.push_back(pcmDevice); __end: if (name != nullptr) free(name); if (descr != nullptr) free(descr); if (io != nullptr) free(io); n++; } snd_device_name_free_hint(hints); return result; } } // namespace playersnapcast-0.28.0/client/player/alsa_player.hpp000066400000000000000000000051071461051111600211730ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "player.hpp" // 3rd party headers #include #include #include // standard headers #include #include #include namespace player { static constexpr auto ALSA = "alsa"; /// Audio Player /** * Audio player implementation using Alsa */ class AlsaPlayer : public Player { public: AlsaPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); ~AlsaPlayer() override; void start() override; void stop() override; /// List the system's audio output devices static std::vector pcm_list(); protected: void worker() override; bool needsThread() const override; private: /// initialize alsa and the mixer (if neccessary) void initAlsa(); /// free alsa and optionally the mixer /// @param uninit_mixer free the mixer void uninitAlsa(bool uninit_mixer); bool getAvailDelay(snd_pcm_sframes_t& avail, snd_pcm_sframes_t& delay); void initMixer(); void uninitMixer(); bool getHardwareVolume(Volume& volume) override; void setHardwareVolume(const Volume& volume) override; void waitForEvent(); snd_pcm_t* handle_; snd_ctl_t* ctl_; snd_mixer_t* mixer_; snd_mixer_elem_t* elem_; std::string mixer_name_; std::string mixer_device_; std::unique_ptr> fd_; std::vector buffer_; snd_pcm_uframes_t frames_; boost::asio::posix::stream_descriptor sd_; std::chrono::time_point last_change_; std::recursive_mutex mutex_; boost::asio::steady_timer timer_; std::optional buffer_time_; std::optional periods_; }; } // namespace player snapcast-0.28.0/client/player/coreaudio_player.cpp000066400000000000000000000171601461051111600222220ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2023 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 . ***/ // prototype/interface header file #include "coreaudio_player.hpp" // local headers #include "common/aixlog.hpp" // 3rd party headers #include namespace player { #define NUM_BUFFERS 2 static constexpr auto LOG_TAG = "CoreAudioPlayer"; // http://stackoverflow.com/questions/4863811/how-to-use-audioqueue-to-play-a-sound-for-mac-osx-in-c // https://gist.github.com/andormade/1360885 void callback(void* custom_data, AudioQueueRef queue, AudioQueueBufferRef buffer) { CoreAudioPlayer* player = static_cast(custom_data); player->playerCallback(queue, buffer); } CoreAudioPlayer::CoreAudioPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : Player(io_context, settings, stream), ms_(100), pubStream_(stream) { } CoreAudioPlayer::~CoreAudioPlayer() { } /// TODO: experimental. No output device can be configured yet. std::vector CoreAudioPlayer::pcm_list() { UInt32 propsize; AudioObjectPropertyAddress theAddress = {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}; AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize); int nDevices = propsize / sizeof(AudioDeviceID); AudioDeviceID* devids = new AudioDeviceID[nDevices]; AudioObjectGetPropertyData(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize, devids); std::vector result; for (int i = 0; i < nDevices; ++i) { if (devids[i] == kAudioDeviceUnknown) continue; UInt32 propSize; AudioObjectPropertyAddress theAddress = {kAudioDevicePropertyStreamConfiguration, kAudioDevicePropertyScopeOutput, 0}; if (AudioObjectGetPropertyDataSize(devids[i], &theAddress, 0, NULL, &propSize)) continue; AudioBufferList* buflist = new AudioBufferList[propSize]; if (AudioObjectGetPropertyData(devids[i], &theAddress, 0, NULL, &propSize, buflist)) continue; int channels = 0; for (UInt32 i = 0; i < buflist->mNumberBuffers; ++i) channels += buflist->mBuffers[i].mNumberChannels; delete[] buflist; if (channels == 0) continue; UInt32 maxlen = 1024; char buf[1024]; theAddress = {kAudioDevicePropertyDeviceName, kAudioDevicePropertyScopeOutput, 0}; AudioObjectGetPropertyData(devids[i], &theAddress, 0, NULL, &maxlen, buf); LOG(DEBUG, LOG_TAG) << "device: " << i << ", name: " << buf << ", channels: " << channels << "\n"; result.push_back(PcmDevice(i, buf)); } delete[] devids; return result; } void CoreAudioPlayer::playerCallback(AudioQueueRef queue, AudioQueueBufferRef bufferRef) { /// Estimate the playout delay by checking the number of frames left in the buffer /// and add ms_ (= complete buffer size). Based on trying. AudioTimeStamp timestamp; AudioQueueGetCurrentTime(queue, timeLine_, ×tamp, NULL); size_t bufferedFrames = (frames_ - ((uint64_t)timestamp.mSampleTime % frames_)) % frames_; size_t bufferedMs = bufferedFrames * 1000 / pubStream_->getFormat().rate() + (ms_ * (NUM_BUFFERS - 1)); /// 15ms DAC delay. Based on trying. bufferedMs += 15; // LOG(INFO, LOG_TAG) << "buffered: " << bufferedFrames << ", ms: " << bufferedMs << ", mSampleTime: " << timestamp.mSampleTime << "\n"; /// TODO: sometimes this bufferedMS or AudioTimeStamp wraps around 1s (i.e. we're 1s out of sync (behind)) and recovers later on chronos::usec delay(bufferedMs * 1000); char* buffer = (char*)bufferRef->mAudioData; if (!pubStream_->getPlayerChunkOrSilence(buffer, delay, frames_)) { if (chronos::getTickCount() - lastChunkTick > 5000) { LOG(NOTICE, LOG_TAG) << "No chunk received for 5000ms. Closing Audio Queue.\n"; uninitAudioQueue(queue); return; } // LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n"; } else { lastChunkTick = chronos::getTickCount(); adjustVolume(buffer, frames_); } // OSStatus status = AudioQueueEnqueueBuffer(queue, bufferRef, 0, NULL); if (!active_) { uninitAudioQueue(queue); } } bool CoreAudioPlayer::needsThread() const { return true; } void CoreAudioPlayer::worker() { while (active_) { if (pubStream_->waitForChunk(std::chrono::milliseconds(100))) { try { initAudioQueue(); } catch (const std::exception& e) { LOG(ERROR, LOG_TAG) << "Exception in worker: " << e.what() << "\n"; chronos::sleep(100); } } chronos::sleep(100); } } void CoreAudioPlayer::initAudioQueue() { const SampleFormat& sampleFormat = pubStream_->getFormat(); AudioStreamBasicDescription format; format.mSampleRate = sampleFormat.rate(); format.mFormatID = kAudioFormatLinearPCM; format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; // | kAudioFormatFlagIsPacked; format.mBitsPerChannel = sampleFormat.bits(); format.mChannelsPerFrame = sampleFormat.channels(); format.mBytesPerFrame = sampleFormat.frameSize(); format.mFramesPerPacket = 1; format.mBytesPerPacket = format.mBytesPerFrame * format.mFramesPerPacket; format.mReserved = 0; AudioQueueRef queue; AudioQueueNewOutput(&format, callback, this, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &queue); AudioQueueCreateTimeline(queue, &timeLine_); // Apple recommends this as buffer size: // https://developer.apple.com/library/content/documentation/MusicAudio/Conceptual/CoreAudioOverview/CoreAudioEssentials/CoreAudioEssentials.html // static const int maxBufferSize = 0x10000; // limit maximum size to 64K // static const int minBufferSize = 0x4000; // limit minimum size to 16K // // For 100ms @ 48000:16:2 we have 19.2K // frames: 4800, ms: 100, buffer size: 19200 frames_ = (sampleFormat.rate() * ms_) / 1000; ms_ = frames_ * 1000 / sampleFormat.rate(); buff_size_ = frames_ * sampleFormat.frameSize(); LOG(INFO, LOG_TAG) << "frames: " << frames_ << ", ms: " << ms_ << ", buffer size: " << buff_size_ << "\n"; AudioQueueBufferRef buffers[NUM_BUFFERS]; for (int i = 0; i < NUM_BUFFERS; i++) { AudioQueueAllocateBuffer(queue, buff_size_, &buffers[i]); buffers[i]->mAudioDataByteSize = buff_size_; callback(this, queue, buffers[i]); } LOG(DEBUG, LOG_TAG) << "CoreAudioPlayer::worker\n"; AudioQueueCreateTimeline(queue, &timeLine_); AudioQueueStart(queue, NULL); CFRunLoopRun(); } void CoreAudioPlayer::uninitAudioQueue(AudioQueueRef queue) { AudioQueueStop(queue, false); AudioQueueDispose(queue, false); pubStream_->clearChunks(); CFRunLoopStop(CFRunLoopGetCurrent()); } } // namespace player snapcast-0.28.0/client/player/coreaudio_player.hpp000066400000000000000000000035411461051111600222250ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2022 Johannes Pohl This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ***/ #ifndef CORE_AUDIO_PLAYER_HPP #define CORE_AUDIO_PLAYER_HPP // local headers #include "player.hpp" // 3rd party headers #include #include #include namespace player { static constexpr auto COREAUDIO = "coreaudio"; /// Audio Player /** * Audio player implementation using CoreAudio * * Warning: * * !! This player is experimental and might not be maintained !! * */ class CoreAudioPlayer : public Player { public: CoreAudioPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); virtual ~CoreAudioPlayer(); void playerCallback(AudioQueueRef queue, AudioQueueBufferRef bufferRef); static std::vector pcm_list(); protected: void worker() override; bool needsThread() const override; void initAudioQueue(); void uninitAudioQueue(AudioQueueRef queue); AudioQueueTimelineRef timeLine_; size_t ms_; size_t frames_; size_t buff_size_; std::shared_ptr pubStream_; long lastChunkTick; }; } // namespace player #endif snapcast-0.28.0/client/player/file_player.cpp000066400000000000000000000077611461051111600211750ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "file_player.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "common/utils/string_utils.hpp" // 3rd party headers // standard headers using namespace std; namespace player { static constexpr auto LOG_TAG = "FilePlayer"; static constexpr auto kDefaultBuffer = 50ms; static constexpr auto kDescription = "Raw PCM file output"; std::vector FilePlayer::pcm_list(const std::string& parameter) { auto params = utils::string::split_pairs(parameter, ',', '='); string filename; if (params.find("filename") != params.end()) filename = params["filename"]; if (filename.empty()) filename = "stdout"; return {PcmDevice{0, filename, kDescription}}; } FilePlayer::FilePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : Player(io_context, settings, stream), timer_(io_context), file_(nullptr) { auto params = utils::string::split_pairs(settings.parameter, ',', '='); string filename; if (params.find("filename") != params.end()) filename = params["filename"]; if (filename.empty() || (filename == "stdout")) { file_.reset(stdout, [](auto p) { std::ignore = p; }); } else if (filename == "stderr") { file_.reset(stderr, [](auto p) { std::ignore = p; }); } else if (filename != "null") { std::string mode = "w"; if (params.find("mode") != params.end()) mode = params["mode"]; if ((mode != "w") && (mode != "a")) throw SnapException("Mode must be w (write) or a (append)"); mode += "b"; file_.reset(fopen(filename.c_str(), mode.c_str()), [](auto p) { fclose(p); }); if (!file_) throw SnapException("Error opening file: '" + filename + "', error: " + cpt::to_string(errno)); } } FilePlayer::~FilePlayer() { LOG(DEBUG, LOG_TAG) << "Destructor\n"; stop(); } bool FilePlayer::needsThread() const { return false; } void FilePlayer::requestAudio() { auto numFrames = static_cast(stream_->getFormat().msRate() * kDefaultBuffer.count()); auto needed = numFrames * stream_->getFormat().frameSize(); if (buffer_.size() < needed) buffer_.resize(needed); if (!stream_->getPlayerChunkOrSilence(buffer_.data(), 10ms, numFrames)) { // LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n"; } else { adjustVolume(static_cast(buffer_.data()), numFrames); } if (file_) { fwrite(buffer_.data(), 1, needed, file_.get()); fflush(file_.get()); } loop(); } void FilePlayer::loop() { next_request_ += kDefaultBuffer; auto now = std::chrono::steady_clock::now(); if (next_request_ < now) next_request_ = now + 1ms; timer_.expires_at(next_request_); timer_.async_wait( [this](boost::system::error_code ec) { if (ec) return; requestAudio(); }); } void FilePlayer::start() { next_request_ = std::chrono::steady_clock::now(); loop(); } void FilePlayer::stop() { LOG(INFO, LOG_TAG) << "Stop\n"; timer_.cancel(); } } // namespace player snapcast-0.28.0/client/player/file_player.hpp000066400000000000000000000034051461051111600211710ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2022 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 FILE_PLAYER_HPP #define FILE_PLAYER_HPP // local headers #include "player.hpp" // 3rd party headers #include // standard headers #include #include namespace player { static constexpr auto FILE = "file"; /// File Player /// Used for testing and doesn't even write the received audio to file at the moment, /// but just discards it class FilePlayer : public Player { public: FilePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); virtual ~FilePlayer(); void start() override; void stop() override; /// List the dummy file PCM device static std::vector pcm_list(const std::string& parameter); protected: void requestAudio(); void loop(); bool needsThread() const override; boost::asio::steady_timer timer_; std::vector buffer_; std::chrono::time_point next_request_; std::shared_ptr<::FILE> file_; }; } // namespace player #endif snapcast-0.28.0/client/player/oboe_player.cpp000066400000000000000000000173341461051111600211770ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "oboe_player.hpp" // local headers #include "common/aixlog.hpp" #include "common/str_compat.hpp" // 3rd party headers // standard headers #include using namespace std; namespace player { static constexpr auto LOG_TAG = "OboePlayer"; static constexpr double kDefaultLatency = 50; OboePlayer::OboePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : Player(io_context, settings, stream) { LOG(DEBUG, LOG_TAG) << "Contructor\n"; LOG(INFO, LOG_TAG) << "Init start\n"; char* env = getenv("SAMPLE_RATE"); if (env) oboe::DefaultStreamValues::SampleRate = cpt::stoi(env, oboe::DefaultStreamValues::SampleRate); env = getenv("FRAMES_PER_BUFFER"); if (env) oboe::DefaultStreamValues::FramesPerBurst = cpt::stoi(env, oboe::DefaultStreamValues::FramesPerBurst); LOG(INFO, LOG_TAG) << "DefaultStreamValues::SampleRate: " << oboe::DefaultStreamValues::SampleRate << ", DefaultStreamValues::FramesPerBurst: " << oboe::DefaultStreamValues::FramesPerBurst << "\n"; auto result = openStream(); LOG(INFO, LOG_TAG) << "BufferSizeInFrames: " << out_stream_->getBufferSizeInFrames() << ", FramesPerBurst: " << out_stream_->getFramesPerBurst() << "\n"; if (result != oboe::Result::OK) LOG(ERROR, LOG_TAG) << "Error building AudioStream: " << oboe::convertToText(result) << "\n"; LOG(INFO, LOG_TAG) << "Init done\n"; } OboePlayer::~OboePlayer() { LOG(DEBUG, LOG_TAG) << "Destructor\n"; stop(); auto result = out_stream_->stop(std::chrono::nanoseconds(100ms).count()); if (result != oboe::Result::OK) LOG(ERROR, LOG_TAG) << "Error in AudioStream::stop: " << oboe::convertToText(result) << "\n"; result = out_stream_->close(); if (result != oboe::Result::OK) LOG(ERROR, LOG_TAG) << "Error in AudioStream::stop: " << oboe::convertToText(result) << "\n"; } oboe::Result OboePlayer::openStream() { oboe::SharingMode sharing_mode = oboe::SharingMode::Shared; if (settings_.sharing_mode == ClientSettings::SharingMode::exclusive) sharing_mode = oboe::SharingMode::Exclusive; // The builder set methods can be chained for convenience. oboe::AudioStreamBuilder builder; auto result = builder.setSharingMode(sharing_mode) ->setPerformanceMode(oboe::PerformanceMode::None) ->setChannelCount(stream_->getFormat().channels()) ->setSampleRate(stream_->getFormat().rate()) ->setFormat(oboe::AudioFormat::I16) ->setDataCallback(this) ->setErrorCallback(this) ->setDirection(oboe::Direction::Output) //->setFramesPerCallback((8 * stream->getFormat().rate) / 1000) //->setFramesPerCallback(2 * oboe::DefaultStreamValues::FramesPerBurst) //->setFramesPerCallback(960) // 2*192) ->openStream(out_stream_); if (out_stream_->getAudioApi() == oboe::AudioApi::AAudio) { LOG(INFO, LOG_TAG) << "AudioApi: AAudio\n"; // mLatencyTuner = std::make_unique(*out_stream_); mLatencyTuner = nullptr; } else { LOG(INFO, LOG_TAG) << "AudioApi: OpenSL\n"; out_stream_->setBufferSizeInFrames(4 * out_stream_->getFramesPerBurst()); } return result; } bool OboePlayer::needsThread() const { return false; } double OboePlayer::getCurrentOutputLatencyMillis() const { // Get the time that a known audio frame was presented for playing auto result = out_stream_->getTimestamp(CLOCK_MONOTONIC); double outputLatencyMillis = kDefaultLatency; const int64_t kNanosPerMillisecond = 1000000; if (result == oboe::Result::OK) { oboe::FrameTimestamp playedFrame = result.value(); // Get the write index for the next audio frame int64_t writeIndex = out_stream_->getFramesWritten(); // Calculate the number of frames between our known frame and the write index int64_t frameIndexDelta = writeIndex - playedFrame.position; // Calculate the time which the next frame will be presented int64_t frameTimeDelta = (frameIndexDelta * oboe::kNanosPerSecond) / (out_stream_->getSampleRate()); int64_t nextFramePresentationTime = playedFrame.timestamp + frameTimeDelta; // Assume that the next frame will be written at the current time using namespace std::chrono; int64_t nextFrameWriteTime = duration_cast(steady_clock::now().time_since_epoch()).count(); // Calculate the latency outputLatencyMillis = static_cast(nextFramePresentationTime - nextFrameWriteTime) / kNanosPerMillisecond; } else { // LOG(ERROR, LOG_TAG) << "Error calculating latency: " << oboe::convertToText(result.error()) << "\n"; } return outputLatencyMillis; } oboe::DataCallbackResult OboePlayer::onAudioReady(oboe::AudioStream* /*oboeStream*/, void* audioData, int32_t numFrames) { if (mLatencyTuner) mLatencyTuner->tune(); double output_latency = getCurrentOutputLatencyMillis(); // LOG(INFO, LOG_TAG) << "getCurrentOutputLatencyMillis: " << output_latency << ", frames: " << numFrames << "\n"; chronos::usec delay(static_cast(output_latency * 1000.)); if (!stream_->getPlayerChunkOrSilence(audioData, delay, numFrames)) { // LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n"; } else { adjustVolume(static_cast(audioData), numFrames); } return oboe::DataCallbackResult::Continue; } void OboePlayer::onErrorBeforeClose(oboe::AudioStream* oboeStream, oboe::Result error) { std::ignore = oboeStream; LOG(INFO, LOG_TAG) << "onErrorBeforeClose: " << oboe::convertToText(error) << "\n"; stop(); } void OboePlayer::onErrorAfterClose(oboe::AudioStream* oboeStream, oboe::Result error) { // Tech Note: Disconnected Streams and Plugin Issues // https://github.com/google/oboe/blob/master/docs/notes/disconnect.md std::ignore = oboeStream; LOG(INFO, LOG_TAG) << "onErrorAfterClose: " << oboe::convertToText(error) << "\n"; auto result = openStream(); if (result != oboe::Result::OK) LOG(ERROR, LOG_TAG) << "Error building AudioStream: " << oboe::convertToText(result) << "\n"; start(); } void OboePlayer::start() { // Typically, start the stream after querying some stream information, as well as some input from the user LOG(INFO, LOG_TAG) << "Start\n"; auto result = out_stream_->requestStart(); if (result != oboe::Result::OK) LOG(ERROR, LOG_TAG) << "Error in requestStart: " << oboe::convertToText(result) << "\n"; } void OboePlayer::stop() { LOG(INFO, LOG_TAG) << "Stop\n"; auto result = out_stream_->requestStop(); if (result != oboe::Result::OK) LOG(ERROR, LOG_TAG) << "Error in requestStop: " << oboe::convertToText(result) << "\n"; } } // namespace player snapcast-0.28.0/client/player/oboe_player.hpp000066400000000000000000000040131461051111600211720ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2022 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 OBOE_PLAYER_HPP #define OBOE_PLAYER_HPP // local headers #include "player.hpp" // 3rd party headers #include #include // standard headers namespace player { static constexpr auto OBOE = "oboe"; /// Android Oboe Audio Player /** * Player implementation for Android Oboe */ class OboePlayer : public Player, public oboe::AudioStreamDataCallback, public oboe::AudioStreamErrorCallback { public: OboePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); virtual ~OboePlayer(); void start() override; void stop() override; protected: // AudioStreamDataCallback overrides oboe::DataCallbackResult onAudioReady(oboe::AudioStream* oboeStream, void* audioData, int32_t numFrames) override; // AudioStreamErrorCallback overrides void onErrorBeforeClose(oboe::AudioStream* oboeStream, oboe::Result error) override; void onErrorAfterClose(oboe::AudioStream* oboeStream, oboe::Result error) override; protected: oboe::Result openStream(); double getCurrentOutputLatencyMillis() const; bool needsThread() const override; std::shared_ptr out_stream_; std::unique_ptr mLatencyTuner; }; } // namespace player #endif snapcast-0.28.0/client/player/opensl_player.cpp000066400000000000000000000331371461051111600215520ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "opensl_player.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" // 3rd party headers // standard headers #include using namespace std; namespace player { static constexpr auto LOG_TAG = "OpenSlPlayer"; static constexpr auto kPhaseInit = "Init"; static constexpr auto kPhaseStart = "Start"; static constexpr auto kPhaseStop = "Stop"; // http://stackoverflow.com/questions/35730050/android-with-nexus-6-how-to-avoid-decreased-opensl-audio-thread-priority-rela?rq=1 // source: https://github.com/hrydgard/native/blob/master/android/native-audio-so.cpp // https://android.googlesource.com/platform/development/+/c21a505/ndk/platforms/android-9/samples/native-audio/jni/native-audio-jni.c // This callback handler is called every time a buffer finishes playing. // The documentation available is very unclear about how to best manage buffers. // I've chosen to this approach: Instantly enqueue a buffer that was rendered to the last time, // and then render the next. Hopefully it's okay to spend time in this callback after having enqueued. static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* context) { OpenslPlayer* player = static_cast(context); player->playerCallback(bq); } OpenslPlayer::OpenslPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : Player(io_context, settings, stream), engineObject(nullptr), engineEngine(nullptr), outputMixObject(nullptr), bqPlayerObject(nullptr), bqPlayerPlay(nullptr), bqPlayerBufferQueue(nullptr), bqPlayerVolume(nullptr), curBuffer(0), ms_(50), buff_size(0), pubStream_(stream) { initOpensl(); } OpenslPlayer::~OpenslPlayer() { uninitOpensl(); } void OpenslPlayer::playerCallback(SLAndroidSimpleBufferQueueItf bq) { if (bq != bqPlayerBufferQueue) { LOG(ERROR, LOG_TAG) << "Wrong bq!\n"; return; } if (!active_) return; chronos::usec delay(ms_ * 1000); if (!pubStream_->getPlayerChunkOrSilence(buffer[curBuffer], delay, frames_)) { // LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n"; } else { adjustVolume(buffer[curBuffer], frames_); } while (active_) { SLresult result = (*bq)->Enqueue(bq, buffer[curBuffer], buff_size); if (result == SL_RESULT_BUFFER_INSUFFICIENT) chronos::sleep(1); else break; } curBuffer ^= 1; // Switch buffer } std::string OpenslPlayer::resultToString(SLresult result) const { switch (result) { case SL_RESULT_SUCCESS: return "SL_RESULT_SUCCESS"; case SL_RESULT_PRECONDITIONS_VIOLATED: return "SL_RESULT_PRECONDITIONS_VIOLATED"; case SL_RESULT_PARAMETER_INVALID: return "SL_RESULT_PARAMETER_INVALID"; case SL_RESULT_MEMORY_FAILURE: return "SL_RESULT_MEMORY_FAILURE"; case SL_RESULT_RESOURCE_ERROR: return "SL_RESULT_RESOURCE_ERROR"; case SL_RESULT_RESOURCE_LOST: return "SL_RESULT_RESOURCE_LOST"; case SL_RESULT_IO_ERROR: return "SL_RESULT_IO_ERROR"; case SL_RESULT_BUFFER_INSUFFICIENT: return "SL_RESULT_BUFFER_INSUFFICIENT"; case SL_RESULT_CONTENT_CORRUPTED: return "SL_RESULT_CONTENT_CORRUPTED"; case SL_RESULT_CONTENT_UNSUPPORTED: return "SL_RESULT_CONTENT_UNSUPPORTED"; case SL_RESULT_CONTENT_NOT_FOUND: return "SL_RESULT_CONTENT_NOT_FOUND"; case SL_RESULT_PERMISSION_DENIED: return "SL_RESULT_PERMISSION_DENIED"; case SL_RESULT_FEATURE_UNSUPPORTED: return "SL_RESULT_FEATURE_UNSUPPORTED"; case SL_RESULT_INTERNAL_ERROR: return "SL_RESULT_INTERNAL_ERROR"; case SL_RESULT_UNKNOWN_ERROR: return "SL_RESULT_UNKNOWN_ERROR"; case SL_RESULT_OPERATION_ABORTED: return "SL_RESULT_OPERATION_ABORTED"; case SL_RESULT_CONTROL_LOST: return "SL_RESULT_CONTROL_LOST"; default: return "UNKNOWN"; } } bool OpenslPlayer::needsThread() const { return false; } void OpenslPlayer::throwUnsuccess(const std::string& phase, const std::string& what, SLresult result) { if (SL_RESULT_SUCCESS == result) return; stringstream ss; ss << phase << " failed, operation: " << what << ", result: " << resultToString(result) << "(" << result << ")"; throw SnapException(ss.str()); } void OpenslPlayer::initOpensl() { if (active_) return; LOG(INFO, LOG_TAG) << "Init start\n"; const SampleFormat& format = stream_->getFormat(); frames_ = format.rate() / (1000 / ms_); // * format.channels(); // 1920; // 48000 * 2 / 50 // => 50ms buff_size = frames_ * format.frameSize() /* 2 -> sample size */; LOG(INFO, LOG_TAG) << "frames: " << frames_ << ", channels: " << format.channels() << ", rate: " << format.rate() << ", buff: " << buff_size << "\n"; SLresult result; // create engine SLEngineOption engineOption[] = {{(SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE}}; result = slCreateEngine(&engineObject, 1, engineOption, 0, nullptr, nullptr); throwUnsuccess(kPhaseInit, "slCreateEngine", result); result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); throwUnsuccess(kPhaseInit, "EngineObject::Realize", result); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); throwUnsuccess(kPhaseInit, "EngineObject::GetInterface", result); result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, 0, 0); throwUnsuccess(kPhaseInit, "EngineEngine::CreateOutputMix", result); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); throwUnsuccess(kPhaseInit, "OutputMixObject::Realize", result); SLuint32 samplesPerSec = SL_SAMPLINGRATE_48; switch (format.rate()) { case 8000: samplesPerSec = SL_SAMPLINGRATE_8; break; case 11025: samplesPerSec = SL_SAMPLINGRATE_11_025; break; case 16000: samplesPerSec = SL_SAMPLINGRATE_16; break; case 22050: samplesPerSec = SL_SAMPLINGRATE_22_05; break; case 24000: samplesPerSec = SL_SAMPLINGRATE_24; break; case 32000: samplesPerSec = SL_SAMPLINGRATE_32; break; case 44100: samplesPerSec = SL_SAMPLINGRATE_44_1; break; case 48000: samplesPerSec = SL_SAMPLINGRATE_48; break; case 64000: samplesPerSec = SL_SAMPLINGRATE_64; break; case 88200: samplesPerSec = SL_SAMPLINGRATE_88_2; break; case 96000: samplesPerSec = SL_SAMPLINGRATE_96; break; case 192000: samplesPerSec = SL_SAMPLINGRATE_192; break; default: throw SnapException("Sample rate not supported"); } SLuint32 bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; SLuint32 containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; switch (format.bits()) { case 8: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_8; containerSize = SL_PCMSAMPLEFORMAT_FIXED_8; break; case 16: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; break; case 24: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_24; containerSize = SL_PCMSAMPLEFORMAT_FIXED_32; break; case 32: bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_32; containerSize = SL_PCMSAMPLEFORMAT_FIXED_32; break; default: throw SnapException("Unsupported sample format: " + cpt::to_string(format.bits())); } SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_pcm = { SL_DATAFORMAT_PCM, format.channels(), samplesPerSec, bitsPerSample, containerSize, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN}; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, nullptr}; // create audio player const SLInterfaceID ids[3] = {SL_IID_ANDROIDCONFIGURATION, SL_IID_PLAY, SL_IID_BUFFERQUEUE}; //, SL_IID_VOLUME}; const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; //, SL_BOOLEAN_TRUE}; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 3, ids, req); throwUnsuccess(kPhaseInit, "Engine::CreateAudioPlayer", result); SLAndroidConfigurationItf playerConfig; result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_ANDROIDCONFIGURATION, &playerConfig); throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result); SLint32 streamType = SL_ANDROID_STREAM_MEDIA; //// SLint32 streamType = SL_ANDROID_STREAM_VOICE; result = (*playerConfig)->SetConfiguration(playerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32)); throwUnsuccess(kPhaseInit, "PlayerConfig::SetConfiguration", result); // Set the performance mode. SLuint32 performanceMode = SL_ANDROID_PERFORMANCE_NONE; result = (*playerConfig)->SetConfiguration(playerConfig, SL_ANDROID_KEY_PERFORMANCE_MODE, &performanceMode, sizeof(performanceMode)); result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); throwUnsuccess(kPhaseInit, "PlayerObject::Realize", result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result); result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, this); throwUnsuccess(kPhaseInit, "PlayerBufferQueue::RegisterCallback", result); // result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume); // throwUnsuccess("PlayerObject::GetInterface", result); result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PAUSED); throwUnsuccess(kPhaseInit, "PlayerPlay::SetPlayState", result); // Render and enqueue a first buffer. (or should we just play the buffer empty?) curBuffer = 0; buffer[0] = new char[buff_size]; buffer[1] = new char[buff_size]; active_ = true; memset(buffer[curBuffer], 0, buff_size); result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer[curBuffer], sizeof(buffer[curBuffer])); throwUnsuccess(kPhaseInit, "PlayerBufferQueue::Enqueue", result); curBuffer ^= 1; LOG(INFO, LOG_TAG) << "Init done\n"; } void OpenslPlayer::uninitOpensl() { // if (!active_) // return; LOG(INFO, LOG_TAG) << "uninitOpensl\n"; SLresult result; LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - stopping playback\n"; if (bqPlayerPlay != nullptr) { result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED); if (SL_RESULT_SUCCESS != result) LOG(ERROR, LOG_TAG) << "SetPlayState failed\n"; } LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - deleting player object\n"; if (bqPlayerObject != nullptr) { (*bqPlayerObject)->Destroy(bqPlayerObject); bqPlayerObject = nullptr; bqPlayerPlay = nullptr; bqPlayerBufferQueue = nullptr; bqPlayerVolume = nullptr; } LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - deleting mix object\n"; if (outputMixObject != nullptr) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = nullptr; } LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - deleting engine object\n"; if (engineObject != nullptr) { (*engineObject)->Destroy(engineObject); engineObject = nullptr; engineEngine = nullptr; } delete[] buffer[0]; buffer[0] = nullptr; delete[] buffer[1]; buffer[1] = nullptr; LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - finished\n"; active_ = false; } void OpenslPlayer::start() { SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); throwUnsuccess(kPhaseStart, "PlayerPlay::SetPlayState", result); } void OpenslPlayer::stop() { SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED); (*bqPlayerBufferQueue)->Clear(bqPlayerBufferQueue); throwUnsuccess(kPhaseStop, "PlayerPlay::SetPlayState", result); } } // namespace player snapcast-0.28.0/client/player/opensl_player.hpp000066400000000000000000000043031461051111600215500ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2022 Johannes Pohl This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ***/ #ifndef OPEN_SL_PLAYER_HPP #define OPEN_SL_PLAYER_HPP // local headers #include "player.hpp" // 3rd party headers #include #include // standard headers #include namespace player { static constexpr auto OPENSL = "opensl"; typedef int (*AndroidAudioCallback)(short* buffer, int num_samples); /// OpenSL Audio Player /** * Player implementation for OpenSL (e.g. Android) */ class OpenslPlayer : public Player { public: OpenslPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); virtual ~OpenslPlayer(); void start() override; void stop() override; void playerCallback(SLAndroidSimpleBufferQueueItf bq); protected: void initOpensl(); void uninitOpensl(); bool needsThread() const override; void throwUnsuccess(const std::string& phase, const std::string& what, SLresult result); std::string resultToString(SLresult result) const; // engine interfaces SLObjectItf engineObject; SLEngineItf engineEngine; SLObjectItf outputMixObject; // buffer queue player interfaces SLObjectItf bqPlayerObject; SLPlayItf bqPlayerPlay; SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue; SLVolumeItf bqPlayerVolume; // Double buffering. int curBuffer; char* buffer[2]; size_t ms_; size_t frames_; size_t buff_size; std::shared_ptr pubStream_; }; } // namespace player #endif snapcast-0.28.0/client/player/pcm_device.hpp000066400000000000000000000022431461051111600207730ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2020 Johannes Pohl This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ***/ #ifndef PCM_DEVICE_HPP #define PCM_DEVICE_HPP #include namespace player { static constexpr char DEFAULT_DEVICE[] = "default"; struct PcmDevice { PcmDevice() : idx(-1), name(DEFAULT_DEVICE){}; PcmDevice(int idx, const std::string& name, const std::string& description = "") : idx(idx), name(name), description(description){}; int idx; std::string name; std::string description; }; } // namespace player #endif snapcast-0.28.0/client/player/player.cpp000066400000000000000000000227261461051111600201740ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "player.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "common/utils/string_utils.hpp" // 3rd party headers #ifdef SUPPORTS_VOLUME_SCRIPT #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Wunused-result" #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wmissing-braces" #pragma GCC diagnostic ignored "-Wnarrowing" #pragma GCC diagnostic ignored "-Wc++11-narrowing" #include #include #include #include #pragma GCC diagnostic pop #endif // standard headers #include #include #include #include using namespace std; namespace player { static constexpr auto LOG_TAG = "Player"; Player::Player(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : io_context_(io_context), active_(false), stream_(stream), settings_(settings), volCorrection_(1.0) { string sharing_mode; switch (settings_.sharing_mode) { case ClientSettings::SharingMode::unspecified: sharing_mode = "unspecified"; break; case ClientSettings::SharingMode::exclusive: sharing_mode = "exclusive"; break; case ClientSettings::SharingMode::shared: sharing_mode = "shared"; break; } auto not_empty = [](const std::string& value) -> std::string { if (!value.empty()) return value; else return ""; }; LOG(INFO, LOG_TAG) << "Player name: " << not_empty(settings_.player_name) << ", device: " << not_empty(settings_.pcm_device.name) << ", description: " << not_empty(settings_.pcm_device.description) << ", idx: " << settings_.pcm_device.idx << ", sharing mode: " << sharing_mode << ", parameters: " << not_empty(settings.parameter) << "\n"; string mixer; switch (settings_.mixer.mode) { case ClientSettings::Mixer::Mode::hardware: mixer = "hardware"; break; case ClientSettings::Mixer::Mode::software: mixer = "software"; break; case ClientSettings::Mixer::Mode::script: mixer = "script"; break; case ClientSettings::Mixer::Mode::none: mixer = "none"; break; } LOG(INFO, LOG_TAG) << "Mixer mode: " << mixer << ", parameters: " << not_empty(settings_.mixer.parameter) << "\n"; LOG(INFO, LOG_TAG) << "Sampleformat: " << (settings_.sample_format.isInitialized() ? settings_.sample_format.toString() : stream->getFormat().toString()) << ", stream: " << stream->getFormat().toString() << "\n"; } Player::~Player() { stop(); } void Player::start() { active_ = true; if (needsThread()) playerThread_ = thread(&Player::worker, this); // If hardware mixer is used, send the initial volume to the server, because this is // the volume that is configured by the user on his local device, so we shouldn't change it // on client start up // if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware) // { // if (getHardwareVolume(volume_, muted_)) // { // LOG(DEBUG, LOG_TAG) << "Volume: " << volume_ << ", muted: " << muted_ << "\n"; // notifyVolumeChange(volume_, muted_); // } // } } void Player::stop() { if (active_) { active_ = false; if (playerThread_.joinable()) playerThread_.join(); } } void Player::worker() { } void Player::setHardwareVolume(const Volume& volume) { std::ignore = volume; throw SnapException("Failed to set hardware mixer volume: not supported"); } bool Player::getHardwareVolume(Volume& volume) { std::ignore = volume; throw SnapException("Failed to get hardware mixer volume: not supported"); } void Player::adjustVolume(char* buffer, size_t frames) { std::lock_guard lock(mutex_); double volume = volCorrection_; // apply volume changes only for software mixer // for any other mixer, we might still have to apply the volCorrection_ if (settings_.mixer.mode == ClientSettings::Mixer::Mode::software) { volume = volume_.mute ? 0. : volume_.volume; volume *= volCorrection_; } if (volume != 1.0) { const SampleFormat& sampleFormat = stream_->getFormat(); if (sampleFormat.sampleSize() == 1) adjustVolume(buffer, frames * sampleFormat.channels(), volume); else if (sampleFormat.sampleSize() == 2) adjustVolume(buffer, frames * sampleFormat.channels(), volume); else if (sampleFormat.sampleSize() == 4) adjustVolume(buffer, frames * sampleFormat.channels(), volume); } } // https://cgit.freedesktop.org/pulseaudio/pulseaudio/tree/src/pulse/volume.c#n260 // http://www.robotplanet.dk/audio/audio_gui_design/ // https://lists.linuxaudio.org/pipermail/linux-audio-dev/2009-May/thread.html#22198 void Player::setVolume_poly(double volume, double exp) { volume_.volume = std::pow(volume, exp); LOG(DEBUG, LOG_TAG) << "setVolume poly with exp " << exp << ": " << volume << " => " << volume_.volume << "\n"; } // http://stackoverflow.com/questions/1165026/what-algorithms-could-i-use-for-audio-volume-level void Player::setVolume_exp(double volume, double base) { // double base = M_E; // double base = 10.; volume_.volume = (pow(base, volume) - 1) / (base - 1); LOG(DEBUG, LOG_TAG) << "setVolume exp with base " << base << ": " << volume << " => " << volume_.volume << "\n"; } void Player::setVolume(const Volume& volume) { std::lock_guard lock(mutex_); volume_ = volume; if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware) { setHardwareVolume(volume); } else if (settings_.mixer.mode == ClientSettings::Mixer::Mode::software) { string param; string mode = utils::string::split_left(settings_.mixer.parameter, ':', param); double dparam = -1.; if (!param.empty()) { try { dparam = cpt::stod(param); if (dparam < 0) throw SnapException("must be a positive number"); } catch (const std::exception& e) { throw SnapException("Invalid mixer param: " + param + ", error: " + string(e.what())); } } if (mode == "poly") setVolume_poly(volume.volume, (dparam < 0) ? 3. : dparam); else setVolume_exp(volume.volume, (dparam < 0) ? 10. : dparam); } else if (settings_.mixer.mode == ClientSettings::Mixer::Mode::script) { #ifdef SUPPORTS_VOLUME_SCRIPT static std::optional pending_volume_change; static boost::process::child mixer_script_process; if (mixer_script_process.running()) { pending_volume_change = volume; LOG(DEBUG, LOG_TAG) << "Volume mixer script still running, deferring this volume change\n"; } else { try { namespace bp = boost::process; mixer_script_process = bp::child(bp::exe = settings_.mixer.parameter, bp::args = {"--volume", cpt::to_string(volume.volume), "--mute", volume.mute ? "true" : "false"}, bp::on_exit( [&](int ret_val, std::error_code ec) { std::unique_lock lock(mutex_); LOG(DEBUG, LOG_TAG) << "Error code: " << ec.message() << ", i: " << ret_val << "\n"; if (pending_volume_change.has_value()) { Volume v = pending_volume_change.value(); pending_volume_change = std::nullopt; lock.unlock(); setVolume(v); } }), io_context_); } catch (const std::exception& e) { LOG(ERROR, LOG_TAG) << "Failed to run script '" + settings_.mixer.parameter + "', error: " << e.what() << "\n"; pending_volume_change = std::nullopt; } } #else LOG(ERROR, LOG_TAG) << "Mixer mode 'script' not supported\n"; #endif } } } // namespace player snapcast-0.28.0/client/player/player.hpp000066400000000000000000000076061461051111600202010ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "client_settings.hpp" #include "common/endian.hpp" #include "stream.hpp" // 3rd party headers #include // standard headers #include #include #include #include #if !defined(WINDOWS) #define SUPPORTS_VOLUME_SCRIPT #endif namespace player { /// Audio Player /** * Abstract audio player implementation */ class Player { public: struct Volume { double volume{1.0}; bool mute{false}; }; using volume_callback = std::function; Player(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); virtual ~Player(); /// Set audio volume in range [0..1] /// @param volume the volume on range [0..1], muted or not virtual void setVolume(const Volume& volume); /// Called on start, before the first audio sample is sent or any other function is called. /// In case of hardware mixer, it will call getVolume and notify the server about the current volume virtual void start(); /// Called on stop virtual void stop(); /// Sets the hardware volume change callback void setVolumeCallback(const volume_callback& callback) { onVolumeChanged_ = callback; } protected: /// will be run in a thread if needsThread is true virtual void worker(); /// @return true if the worker function should be started in a thread virtual bool needsThread() const = 0; /// get the hardware mixer volume /// @param[out] volume the volume on range [0..1], muted or not /// @return success or not virtual bool getHardwareVolume(Volume& volume); /// set the hardware mixer volume /// @param volume the volume on range [0..1], muted or not /// @param muted muted or not virtual void setHardwareVolume(const Volume& volume); void setVolume_poly(double volume, double exp); void setVolume_exp(double volume, double base); void adjustVolume(char* buffer, size_t frames); /// Notify the server about hardware volume changes /// @param volume the volume in range [0..1] /// @param muted if muted or not void notifyVolumeChange(const Volume& volume) const { if (onVolumeChanged_) onVolumeChanged_(volume); } boost::asio::io_context& io_context_; std::atomic active_; std::shared_ptr stream_; std::thread playerThread_; ClientSettings::Player settings_; Player::Volume volume_; double volCorrection_; volume_callback onVolumeChanged_; mutable std::mutex mutex_; private: template void adjustVolume(char* buffer, size_t count, double volume) { T* bufferT = (T*)buffer; for (size_t n = 0; n < count; ++n) bufferT[n] = endian::swap(static_cast(endian::swap(bufferT[n]) * volume)); } }; inline bool operator==(const Player::Volume& lhs, const Player::Volume& rhs) { return ((lhs.volume == rhs.volume) && (lhs.mute == rhs.mute)); } inline bool operator!=(const Player::Volume& lhs, const Player::Volume& rhs) { return !(lhs == rhs); } } // namespace player snapcast-0.28.0/client/player/pulse_player.cpp000066400000000000000000000505701461051111600214020ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "pulse_player.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "common/utils/logging.hpp" #include "common/utils/string_utils.hpp" // 3rd party headers #include // standard headers #include using namespace std::chrono_literals; using namespace std; namespace player { static constexpr std::chrono::milliseconds BUFFER_TIME = 100ms; static constexpr auto LOG_TAG = "PulsePlayer"; // Example code: // https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/pulseaudio/qaudioinput_pulse.cpp?h=dev // http://www.videolan.org/developers/vlc/modules/audio_output/pulse.c // https://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/Developer/Clients/Samples/AsyncPlayback/ vector PulsePlayer::pcm_list(const std::string& parameter) { auto pa_ml = std::shared_ptr(pa_mainloop_new(), [](pa_mainloop* pa_ml) { pa_mainloop_free(pa_ml); }); pa_mainloop_api* pa_mlapi = pa_mainloop_get_api(pa_ml.get()); auto pa_ctx = std::shared_ptr(pa_context_new(pa_mlapi, "Snapcast"), [](pa_context* pa_ctx) { pa_context_disconnect(pa_ctx); pa_context_unref(pa_ctx); }); std::string pa_server; auto params = utils::string::split_pairs(parameter, ',', '='); if (params.find("server") != params.end()) pa_server = params["server"]; if (pa_context_connect(pa_ctx.get(), pa_server.empty() ? nullptr : pa_server.c_str(), PA_CONTEXT_NOFLAGS, nullptr) < 0) throw SnapException("Failed to connect to PulseAudio context, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get())))); static int pa_ready = 0; pa_context_set_state_callback( pa_ctx.get(), [](pa_context* c, void* userdata) { std::ignore = userdata; pa_context_state_t state = pa_context_get_state(c); switch (state) { case PA_CONTEXT_FAILED: case PA_CONTEXT_TERMINATED: pa_ready = 2; break; case PA_CONTEXT_READY: pa_ready = 1; break; default: break; } }, nullptr); // We can't do anything until PA is ready, so just iterate the mainloop // and continue auto wait_start = std::chrono::steady_clock::now(); while (pa_ready == 0) { auto now = std::chrono::steady_clock::now(); if (now - wait_start > 5s) throw SnapException("Timeout while waiting for PulseAudio to become ready"); if (pa_mainloop_iterate(pa_ml.get(), 1, nullptr) < 0) throw SnapException("Error while waiting for PulseAudio to become ready, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get())))); this_thread::sleep_for(1ms); } if (pa_ready == 2) throw SnapException("PulseAudio context failed, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get())))); static std::vector devices; auto* op = pa_context_get_sink_info_list( pa_ctx.get(), [](pa_context* ctx, const pa_sink_info* i, int eol, void* userdata) mutable { std::ignore = ctx; std::ignore = userdata; // auto self = static_cast(userdata); // If eol is set to a positive number, you're at the end of the list if (eol <= 0) devices.emplace_back(i->index, i->name, i->description); }, nullptr); if (op == nullptr) throw SnapException("PulseAudio get sink info list failed, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get())))); wait_start = std::chrono::steady_clock::now(); while (pa_operation_get_state(op) != PA_OPERATION_DONE) { if (pa_operation_get_state(op) == PA_OPERATION_CANCELED) throw SnapException("PulseAudio operation canceled"); auto now = std::chrono::steady_clock::now(); if (now - wait_start > 2s) break; pa_mainloop_iterate(pa_ml.get(), 1, nullptr); } int max_idx = -1; for (const auto& device : devices) max_idx = std::max(max_idx, device.idx); devices.emplace(devices.begin(), max_idx + 1, DEFAULT_DEVICE, "Let PulseAudio server choose the device"); return devices; } PulsePlayer::PulsePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : Player(io_context, settings, stream), latency_(BUFFER_TIME), pa_ml_(nullptr), pa_ctx_(nullptr), playstream_(nullptr), proplist_(nullptr), server_(std::nullopt) { auto params = utils::string::split_pairs_to_container>(settings.parameter, ',', '='); if (params.find("buffer_time") != params.end()) latency_ = std::chrono::milliseconds(std::max(cpt::stoi(params["buffer_time"].front()), 10)); if (params.find("server") != params.end()) server_ = params["server"].front(); properties_[PA_PROP_MEDIA_ROLE] = "music"; properties_[PA_PROP_APPLICATION_ICON_NAME] = "snapcast"; if (params.find("property") != params.end()) { for (const auto& p : params["property"]) { std::string value; std::string key = utils::string::split_left(p, '=', value); if (!key.empty()) properties_[key] = value; } } for (const auto& property : properties_) { if (!property.second.empty()) LOG(INFO, LOG_TAG) << "Setting property \"" << property.first << "\" to \"" << property.second << "\"\n"; } LOG(INFO, LOG_TAG) << "Using buffer_time: " << latency_.count() / 1000 << " ms, server: " << server_.value_or("default") << "\n"; } PulsePlayer::~PulsePlayer() { LOG(DEBUG, LOG_TAG) << "Destructor\n"; stop(); } bool PulsePlayer::needsThread() const { return true; } void PulsePlayer::worker() { while (active_) { pa_mainloop_run(pa_ml_, nullptr); // if we are still active, wait for a chunk and attempt to reconnect while (active_ && !stream_->waitForChunk(100ms)) { static utils::logging::TimeConditional cond(2s); LOG(DEBUG, LOG_TAG) << cond << "Waiting for a chunk to become available before reconnecting\n"; } while (active_) { LOG(INFO, LOG_TAG) << "Chunk available, reconnecting to pulse\n"; try { connect(); break; } catch (const std::exception& e) { LOG(ERROR, LOG_TAG) << "Exception while connecting to pulse: " << e.what() << endl; disconnect(); chronos::sleep(100); } } } } void PulsePlayer::setHardwareVolume(const Volume& volume) { // if we're not connected to pulse, ignore the hardware volume change as the volume will be set upon reconnect if (playstream_ == nullptr) return; last_change_ = std::chrono::steady_clock::now(); pa_cvolume cvolume; if (volume.mute) pa_cvolume_set(&cvolume, stream_->getFormat().channels(), PA_VOLUME_MUTED); else pa_cvolume_set(&cvolume, stream_->getFormat().channels(), volume.volume * PA_VOLUME_NORM); pa_context_set_sink_input_volume(pa_ctx_, pa_stream_get_index(playstream_), &cvolume, nullptr, nullptr); } bool PulsePlayer::getHardwareVolume(Volume& volume) { // This is called during start to send the initial volume to the server // Because getting the volume works async, we return false here // and instead trigger volume notification in pa_context_subscribe std::ignore = volume; return false; } void PulsePlayer::triggerVolumeUpdate() { pa_context_get_sink_input_info( pa_ctx_, pa_stream_get_index(playstream_), [](pa_context* ctx, const pa_sink_input_info* info, int eol, void* userdata) { std::ignore = ctx; LOG(DEBUG, LOG_TAG) << "pa_context_get_sink_info_by_index info: " << (info != nullptr) << ", eol: " << eol << "\n"; if (info != nullptr) { auto* self = static_cast(userdata); self->volume_.volume = static_cast(pa_cvolume_avg(&(info->volume))) / static_cast(PA_VOLUME_NORM); self->volume_.mute = (info->mute != 0); LOG(DEBUG, LOG_TAG) << "Volume changed: " << self->volume_.volume << ", muted: " << self->volume_.mute << "\n"; auto now = std::chrono::steady_clock::now(); if (now - self->last_change_ < 1s) { LOG(DEBUG, LOG_TAG) << "Last volume change by server: " << std::chrono::duration_cast(now - self->last_change_).count() << " ms => ignoring volume change\n"; return; } self->notifyVolumeChange(self->volume_); } }, this); } void PulsePlayer::subscribeCallback(pa_context* ctx, pa_subscription_event_type_t event_type, uint32_t idx) { std::ignore = ctx; LOG(TRACE, LOG_TAG) << "subscribeCallback, event type: " << event_type << ", idx: " << idx << "\n"; unsigned facility = event_type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK; event_type = static_cast(static_cast(event_type) & PA_SUBSCRIPTION_EVENT_TYPE_MASK); if (facility == PA_SUBSCRIPTION_EVENT_SINK_INPUT) { LOG(DEBUG, LOG_TAG) << "event_type: " << event_type << ", facility: " << facility << "\n"; if ((playstream_ != nullptr) && (idx == pa_stream_get_index(playstream_))) triggerVolumeUpdate(); } } void PulsePlayer::underflowCallback(pa_stream* stream) { // We increase the latency by 50% if we get 6 underflows and latency is under 2s // This is very useful for over the network playback that can't handle low latencies underflows_++; LOG(INFO, LOG_TAG) << "undeflow #" << underflows_ << ", latency: " << latency_.count() / 1000 << " ms\n"; if (underflows_ >= 6 && latency_ < 500ms) { latency_ = (latency_ * 3) / 2; bufattr_.maxlength = pa_usec_to_bytes(latency_.count(), &pa_ss_); bufattr_.tlength = pa_usec_to_bytes(latency_.count(), &pa_ss_); pa_stream_set_buffer_attr(stream, &bufattr_, nullptr, nullptr); underflows_ = 0; LOG(INFO, LOG_TAG) << "latency increased to " << latency_.count() / 1000 << " ms\n"; } } void PulsePlayer::stateCallback(pa_context* ctx) { pa_context_state_t state = pa_context_get_state(ctx); string str_state = "unknown"; pa_ready_ = 0; switch (state) { // These are just here for reference case PA_CONTEXT_UNCONNECTED: str_state = "unconnected"; break; case PA_CONTEXT_CONNECTING: str_state = "connecting"; break; case PA_CONTEXT_AUTHORIZING: str_state = "authorizing"; break; case PA_CONTEXT_SETTING_NAME: str_state = "setting name"; break; default: str_state = "unknown"; break; case PA_CONTEXT_FAILED: str_state = "failed"; pa_ready_ = 2; break; case PA_CONTEXT_TERMINATED: str_state = "terminated"; pa_ready_ = 2; break; case PA_CONTEXT_READY: str_state = "ready"; pa_ready_ = 1; break; } LOG(DEBUG, LOG_TAG) << "State changed " << state << ": " << str_state << "\n"; } void PulsePlayer::writeCallback(pa_stream* stream, size_t nbytes) { pa_usec_t usec; int neg; pa_stream_get_latency(stream, &usec, &neg); auto numFrames = nbytes / stream_->getFormat().frameSize(); if (buffer_.size() < nbytes) buffer_.resize(nbytes); // LOG(TRACE, LOG_TAG) << "writeCallback latency " << usec << " us, frames: " << numFrames << "\n"; if (!stream_->getPlayerChunkOrSilence(buffer_.data(), std::chrono::microseconds(usec), numFrames)) { // if we haven't got a chunk for a while, it's time to disconnect from pulse so the sound device // can become idle/suspended. if (chronos::getTickCount() - last_chunk_tick_ > 5000) { LOG(INFO, LOG_TAG) << "No chunk received for 5000ms, disconnecting from pulse.\n"; this->disconnect(); return; } // LOG(TRACE, LOG_TAG) << "Failed to get chunk. Playing silence.\n"; } else { last_chunk_tick_ = chronos::getTickCount(); adjustVolume(static_cast(buffer_.data()), numFrames); } pa_stream_write(stream, buffer_.data(), nbytes, nullptr, 0LL, PA_SEEK_RELATIVE); } void PulsePlayer::start() { LOG(INFO, LOG_TAG) << "Start\n"; this->connect(); Player::start(); } void PulsePlayer::connect() { std::lock_guard lock(mutex_); LOG(INFO, LOG_TAG) << "Connecting to pulse\n"; if (settings_.pcm_device.idx == -1) throw SnapException("Can't open " + settings_.pcm_device.name + ", error: No such device"); const SampleFormat& format = stream_->getFormat(); pa_ss_.rate = format.rate(); pa_ss_.channels = format.channels(); if (format.bits() == 8) pa_ss_.format = PA_SAMPLE_U8; else if (format.bits() == 16) pa_ss_.format = PA_SAMPLE_S16LE; else if ((format.bits() == 24) && (format.sampleSize() == 3)) pa_ss_.format = PA_SAMPLE_S24LE; else if ((format.bits() == 24) && (format.sampleSize() == 4)) pa_ss_.format = PA_SAMPLE_S24_32LE; else if (format.bits() == 32) pa_ss_.format = PA_SAMPLE_S32LE; else throw SnapException("Unsupported sample format \"" + cpt::to_string(format.bits()) + "\""); // Create a mainloop API and connection to the default server pa_ready_ = 0; pa_ml_ = pa_mainloop_new(); pa_mainloop_api* pa_mlapi = pa_mainloop_get_api(pa_ml_); proplist_ = pa_proplist_new(); for (const auto& property : properties_) { if (!property.second.empty()) pa_proplist_sets(proplist_, property.first.c_str(), property.second.c_str()); } pa_ctx_ = pa_context_new_with_proplist(pa_mlapi, "Snapcast", proplist_); const char* server = server_.has_value() ? server_.value().c_str() : nullptr; if (pa_context_connect(pa_ctx_, server, PA_CONTEXT_NOFLAGS, nullptr) < 0) throw SnapException("Failed to connect to PulseAudio context, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx_)))); // This function defines a callback so the server will tell us it's state. // Our callback will wait for the state to be ready. The callback will // modify the variable to 1 so we know when we have a connection and it's // ready. // If there's an error, the callback will set pa_ready to 2 pa_context_set_state_callback( pa_ctx_, [](pa_context* c, void* userdata) { auto* self = static_cast(userdata); self->stateCallback(c); }, this); // We can't do anything until PA is ready, so just iterate the mainloop // and continue auto wait_start = std::chrono::steady_clock::now(); while (pa_ready_ == 0) { auto now = std::chrono::steady_clock::now(); if (now - wait_start > 5s) throw SnapException("Timeout while waiting for PulseAudio to become ready"); if (pa_mainloop_iterate(pa_ml_, 1, nullptr) < 0) throw SnapException("Error while waiting for PulseAudio to become ready, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx_)))); this_thread::sleep_for(1ms); } if (pa_ready_ == 2) throw SnapException("PulseAudio is not ready, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx_)))); playstream_ = pa_stream_new(pa_ctx_, "Playback", &pa_ss_, nullptr); if (playstream_ == nullptr) throw SnapException("Failed to create PulseAudio stream"); if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware) { pa_context_set_subscribe_callback( pa_ctx_, [](pa_context* ctx, pa_subscription_event_type_t event_type, uint32_t idx, void* userdata) { auto* self = static_cast(userdata); self->subscribeCallback(ctx, event_type, idx); }, this); const auto mask = static_cast(PA_SUBSCRIPTION_MASK_SINK_INPUT); pa_context_subscribe( pa_ctx_, mask, [](pa_context* ctx, int success, void* userdata) { std::ignore = ctx; if (success != 0) { auto* self = static_cast(userdata); self->triggerVolumeUpdate(); } }, this); } pa_stream_set_write_callback( playstream_, [](pa_stream* stream, size_t length, void* userdata) { auto* self = static_cast(userdata); self->writeCallback(stream, length); }, this); pa_stream_set_underflow_callback( playstream_, [](pa_stream* stream, void* userdata) { auto* self = static_cast(userdata); self->underflowCallback(stream); }, this); bufattr_.fragsize = pa_usec_to_bytes(latency_.count(), &pa_ss_); bufattr_.maxlength = pa_usec_to_bytes(latency_.count(), &pa_ss_); bufattr_.minreq = static_cast(-1); bufattr_.prebuf = static_cast(-1); bufattr_.tlength = pa_usec_to_bytes(latency_.count(), &pa_ss_); const char* device = nullptr; if (settings_.pcm_device.name != DEFAULT_DEVICE) device = settings_.pcm_device.name.c_str(); int result = pa_stream_connect_playback( playstream_, device, &bufattr_, static_cast(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE), nullptr, nullptr); if (result < 0) { // Old pulse audio servers don't like the ADJUST_LATENCY flag, so retry without that result = pa_stream_connect_playback(playstream_, device, &bufattr_, static_cast(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE), nullptr, nullptr); } if (result < 0) throw SnapException("Failed to connect PulseAudio playback stream"); // we just connected, pretend we got a chunk so we don't immediately disconnect. last_chunk_tick_ = chronos::getTickCount(); } void PulsePlayer::stop() { LOG(INFO, LOG_TAG) << "Stop\n"; this->disconnect(); Player::stop(); } void PulsePlayer::disconnect() { std::lock_guard lock(mutex_); LOG(INFO, LOG_TAG) << "Disconnecting from pulse\n"; if (pa_ml_ != nullptr) { pa_mainloop_quit(pa_ml_, 0); } if (pa_ctx_ != nullptr) { pa_context_disconnect(pa_ctx_); pa_context_unref(pa_ctx_); pa_ctx_ = nullptr; } if (pa_ml_ != nullptr) { pa_mainloop_free(pa_ml_); pa_ml_ = nullptr; } if (playstream_ != nullptr) { pa_stream_set_state_callback(playstream_, nullptr, nullptr); pa_stream_set_read_callback(playstream_, nullptr, nullptr); pa_stream_set_underflow_callback(playstream_, nullptr, nullptr); pa_stream_set_overflow_callback(playstream_, nullptr, nullptr); pa_stream_disconnect(playstream_); pa_stream_unref(playstream_); playstream_ = nullptr; } if (proplist_ != nullptr) { pa_proplist_free(proplist_); proplist_ = nullptr; } } } // namespace player snapcast-0.28.0/client/player/pulse_player.hpp000066400000000000000000000050101461051111600213740ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ #pragma once // local headers #include "player.hpp" // 3rd party headers #include // standard headers #include #include #include #include namespace player { static constexpr auto PULSE = "pulse"; /// File Player /// Used for testing and doesn't even write the received audio to file at the moment, /// but just discards it class PulsePlayer : public Player { public: PulsePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); virtual ~PulsePlayer(); void start() override; void stop() override; /// List the system's audio output devices static std::vector pcm_list(const std::string& parameter); protected: bool needsThread() const override; void worker() override; void connect(); void disconnect(); bool getHardwareVolume(Volume& volume) override; void setHardwareVolume(const Volume& volume) override; void triggerVolumeUpdate(); void underflowCallback(pa_stream* stream); void stateCallback(pa_context* ctx); void writeCallback(pa_stream* stream, size_t nbytes); void subscribeCallback(pa_context* ctx, pa_subscription_event_type_t event_type, uint32_t idx); std::vector buffer_; std::chrono::microseconds latency_; int underflows_ = 0; std::atomic pa_ready_; long last_chunk_tick_; pa_buffer_attr bufattr_; pa_sample_spec pa_ss_; pa_mainloop* pa_ml_; pa_context* pa_ctx_; pa_stream* playstream_; pa_proplist* proplist_; std::optional server_; std::map properties_; // cache of the last volume change std::chrono::time_point last_change_; }; } // namespace player snapcast-0.28.0/client/player/wasapi_player.cpp000066400000000000000000000447171461051111600215440ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // prototype/interface header file #include "wasapi_player.hpp" // local headers #include "common/aixlog.hpp" #include "common/snap_exception.hpp" // 3rd party headers #include #include // standard headers #include #include #include #include #include #include #include using namespace std; using namespace std::chrono; using namespace std::chrono_literals; namespace player { static constexpr auto LOG_TAG = "WASAPI"; template struct COMMemDeleter { void operator()(T* obj) { if (obj != NULL) { CoTaskMemFree(obj); obj = NULL; } } }; template using com_mem_ptr = unique_ptr>; using com_handle = unique_ptr>; const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); const IID IID_IAudioClient = __uuidof(IAudioClient); const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient); const IID IID_IAudioClock = __uuidof(IAudioClock); const IID IID_IAudioEndpointVolume = _uuidof(IAudioEndpointVolume); _COM_SMARTPTR_TYPEDEF(IMMDevice, __uuidof(IMMDevice)); _COM_SMARTPTR_TYPEDEF(IMMDeviceCollection, __uuidof(IMMDeviceCollection)); _COM_SMARTPTR_TYPEDEF(IMMDeviceEnumerator, __uuidof(IMMDeviceEnumerator)); _COM_SMARTPTR_TYPEDEF(IAudioClient, __uuidof(IAudioClient)); _COM_SMARTPTR_TYPEDEF(IPropertyStore, __uuidof(IPropertyStore)); _COM_SMARTPTR_TYPEDEF(IAudioSessionManager, __uuidof(IAudioSessionManager)); _COM_SMARTPTR_TYPEDEF(IAudioSessionControl, __uuidof(IAudioSessionControl)); #define REFTIMES_PER_SEC 10000000 #define REFTIMES_PER_MILLISEC 10000 EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_Device_FriendlyName = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14}; #define CHECK_HR(hres) \ if (FAILED(hres)) \ { \ stringstream ss; \ ss << "HRESULT fault status: " << hex << (hres) << " line " << dec << __LINE__ << endl; \ LOG(FATAL, LOG_TAG) << ss.str(); \ throw SnapException(ss.str()); \ } WASAPIPlayer::WASAPIPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream) : Player(io_context, settings, stream) { HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); CHECK_HR(hr); audioEventListener_ = new AudioSessionEventListener(); } WASAPIPlayer::~WASAPIPlayer() { audioEndpointListener_->UnregisterControlChangeNotify(&audioEndpointVolumeCallback_); WASAPIPlayer::stop(); } inline PcmDevice convertToDevice(int idx, IMMDevicePtr& device) { HRESULT hr; PcmDevice desc; LPWSTR id = NULL; hr = device->GetId(&id); CHECK_HR(hr); IPropertyStorePtr properties = nullptr; hr = device->OpenPropertyStore(STGM_READ, &properties); PROPVARIANT deviceName; PropVariantInit(&deviceName); hr = properties->GetValue(PKEY_Device_FriendlyName, &deviceName); CHECK_HR(hr); desc.idx = idx; // Convert a wide Unicode string to an UTF8 string auto utf8_encode = [](const std::wstring& wstr) { if (wstr.empty()) return std::string(); int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); std::string strTo(size_needed, 0); WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); return strTo; }; desc.name = utf8_encode(id); desc.description = utf8_encode(deviceName.pwszVal); CoTaskMemFree(id); return desc; } vector WASAPIPlayer::pcm_list() { HRESULT hr; IMMDeviceCollectionPtr devices = nullptr; IMMDeviceEnumeratorPtr deviceEnumerator = nullptr; hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (hr != CO_E_ALREADYINITIALIZED) CHECK_HR(hr); hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_SERVER, IID_IMMDeviceEnumerator, (void**)&deviceEnumerator); CHECK_HR(hr); hr = deviceEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices); CHECK_HR(hr); UINT deviceCount; devices->GetCount(&deviceCount); if (deviceCount == 0) throw SnapException("no valid devices"); vector deviceList; { IMMDevicePtr defaultDevice = nullptr; hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice); CHECK_HR(hr); auto dev = convertToDevice(0, defaultDevice); dev.name = DEFAULT_DEVICE; deviceList.push_back(dev); } for (UINT i = 0; i < deviceCount; ++i) { IMMDevicePtr device = nullptr; hr = devices->Item(i, &device); CHECK_HR(hr); deviceList.push_back(convertToDevice(i + 1, device)); } return deviceList; } #pragma warning(push) #pragma warning(disable : 4127) void WASAPIPlayer::worker() { assert(sizeof(char) == sizeof(BYTE)); HRESULT hr; // Create the format specifier com_mem_ptr waveformat((WAVEFORMATEX*)(CoTaskMemAlloc(sizeof(WAVEFORMATEX)))); waveformat->wFormatTag = WAVE_FORMAT_PCM; waveformat->nChannels = stream_->getFormat().channels(); waveformat->nSamplesPerSec = stream_->getFormat().rate(); waveformat->wBitsPerSample = stream_->getFormat().bits(); waveformat->nBlockAlign = waveformat->nChannels * waveformat->wBitsPerSample / 8; waveformat->nAvgBytesPerSec = waveformat->nSamplesPerSec * waveformat->nBlockAlign; waveformat->cbSize = 0; com_mem_ptr waveformatExtended((WAVEFORMATEXTENSIBLE*)(CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE)))); waveformatExtended->Format = *waveformat; waveformatExtended->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; waveformatExtended->Format.cbSize = 22; waveformatExtended->Samples.wValidBitsPerSample = waveformat->wBitsPerSample; waveformatExtended->dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; waveformatExtended->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; // Retrieve the device enumerator IMMDeviceEnumeratorPtr deviceEnumerator = nullptr; hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_SERVER, IID_IMMDeviceEnumerator, (void**)&deviceEnumerator); CHECK_HR(hr); // Register the default playback device (eRender for playback) IMMDevicePtr device = nullptr; if (settings_.pcm_device.idx == 0) { hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device); CHECK_HR(hr); } else { IMMDeviceCollectionPtr devices = nullptr; hr = deviceEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices); CHECK_HR(hr); devices->Item(settings_.pcm_device.idx - 1, &device); } IPropertyStorePtr properties = nullptr; hr = device->OpenPropertyStore(STGM_READ, &properties); CHECK_HR(hr); PROPVARIANT format; hr = properties->GetValue(PKEY_AudioEngine_DeviceFormat, &format); CHECK_HR(hr); PWAVEFORMATEX formatEx = (PWAVEFORMATEX)format.blob.pBlobData; LOG(INFO, LOG_TAG) << "Device accepts format: " << formatEx->nSamplesPerSec << ":" << formatEx->wBitsPerSample << ":" << formatEx->nChannels << "\n"; // Activate the device IAudioClientPtr audioClient = nullptr; hr = device->Activate(IID_IAudioClient, CLSCTX_SERVER, NULL, (void**)&audioClient); CHECK_HR(hr); if (settings_.sharing_mode == ClientSettings::SharingMode::exclusive) { hr = audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, &(waveformatExtended->Format), NULL); CHECK_HR(hr); } IAudioSessionManagerPtr sessionManager = nullptr; // Get the session manager for the endpoint device. hr = device->Activate(__uuidof(IAudioSessionManager), CLSCTX_INPROC_SERVER, NULL, (void**)&sessionManager); CHECK_HR(hr); // Get the control interface for the process-specific audio // session with session GUID = GUID_NULL. This is the session // that an audio stream for a DirectSound, DirectShow, waveOut, // or PlaySound application stream belongs to by default. IAudioSessionControlPtr control = nullptr; hr = sessionManager->GetAudioSessionControl(NULL, 0, &control); CHECK_HR(hr); // register hr = control->RegisterAudioSessionNotification(audioEventListener_); CHECK_HR(hr); hr = device->Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, NULL, (void**)&audioEndpointListener_); audioEndpointListener_->RegisterControlChangeNotify((IAudioEndpointVolumeCallback*)&audioEndpointVolumeCallback_); // Get the device period REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC; hr = audioClient->GetDevicePeriod(NULL, &hnsRequestedDuration); CHECK_HR(hr); LOG(INFO, LOG_TAG) << "Initializing WASAPI in " << (settings_.sharing_mode == ClientSettings::SharingMode::shared ? "shared" : "exclusive") << " mode\n"; _AUDCLNT_SHAREMODE share_mode = settings_.sharing_mode == ClientSettings::SharingMode::shared ? AUDCLNT_SHAREMODE_SHARED : AUDCLNT_SHAREMODE_EXCLUSIVE; DWORD stream_flags = settings_.sharing_mode == ClientSettings::SharingMode::shared ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY : AUDCLNT_STREAMFLAGS_EVENTCALLBACK; // Initialize the client at minimum latency hr = audioClient->Initialize(share_mode, stream_flags, hnsRequestedDuration, hnsRequestedDuration, &(waveformatExtended->Format), NULL); if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { UINT32 alignedBufferSize; hr = audioClient->GetBufferSize(&alignedBufferSize); CHECK_HR(hr); audioClient.Attach(NULL, false); hnsRequestedDuration = (REFERENCE_TIME)((10000.0 * 1000 / waveformatExtended->Format.nSamplesPerSec * alignedBufferSize) + 0.5); hr = device->Activate(IID_IAudioClient, CLSCTX_SERVER, NULL, (void**)&audioClient); CHECK_HR(hr); hr = audioClient->Initialize(share_mode, stream_flags, hnsRequestedDuration, hnsRequestedDuration, &(waveformatExtended->Format), NULL); } CHECK_HR(hr); // Register an event to refill the buffer com_handle eventHandle(CreateEvent(NULL, FALSE, FALSE, NULL), &::CloseHandle); if (eventHandle == NULL) CHECK_HR(E_FAIL); hr = audioClient->SetEventHandle(HANDLE(eventHandle.get())); CHECK_HR(hr); // Get size of buffer UINT32 bufferFrameCount; hr = audioClient->GetBufferSize(&bufferFrameCount); CHECK_HR(hr); // Get the rendering service IAudioRenderClient* renderClient = NULL; hr = audioClient->GetService(IID_IAudioRenderClient, (void**)&renderClient); CHECK_HR(hr); // Grab the clock service IAudioClock* clock = NULL; hr = audioClient->GetService(IID_IAudioClock, (void**)&clock); CHECK_HR(hr); // Boost our priority DWORD taskIndex = 0; com_handle taskHandle(AvSetMmThreadCharacteristics(TEXT("Pro Audio"), &taskIndex), &::AvRevertMmThreadCharacteristics); if (taskHandle == NULL) CHECK_HR(E_FAIL); // And, action! hr = audioClient->Start(); CHECK_HR(hr); size_t bufferSize = bufferFrameCount * waveformatExtended->Format.nBlockAlign; BYTE* buffer; unique_ptr queueBuffer(new char[bufferSize]); UINT64 position = 0, bufferPosition = 0, frequency; clock->GetFrequency(&frequency); while (active_) { DWORD returnVal = WaitForSingleObject(eventHandle.get(), 2000); if (returnVal != WAIT_OBJECT_0) { // stop(); LOG(INFO, LOG_TAG) << "Got timeout waiting for audio device callback\n"; CHECK_HR(ERROR_TIMEOUT); hr = audioClient->Stop(); CHECK_HR(hr); hr = audioClient->Reset(); CHECK_HR(hr); while (active_ && !stream_->waitForChunk(std::chrono::milliseconds(100))) LOG(INFO, LOG_TAG) << "Waiting for chunk\n"; hr = audioClient->Start(); CHECK_HR(hr); bufferPosition = 0; break; } // Thread was sleeping above, double check that we are still running if (!active_) break; // update our volume from IAudioControl if (mode_ == ClientSettings::SharingMode::exclusive) { volCorrection_ = audioEventListener_->getVolume(); // muteOverride = audioEventListener_->getMuted(); // use this for also applying audio mixer mute state } // get audio device volume from IAudioEndpointVolume // float deviceVolume = audioEndpointVolumeCallback.getVolume(); // system volume (for this audio device) // bool deviceMuted = audioEndpointVolumeCallback.getMuted(); // system mute (for this audio device) clock->GetPosition(&position, NULL); UINT32 padding = 0; if (settings_.sharing_mode == ClientSettings::SharingMode::shared) { hr = audioClient->GetCurrentPadding(&padding); CHECK_HR(hr); } int available = bufferFrameCount - padding; if (stream_->getPlayerChunk(queueBuffer.get(), microseconds(((bufferPosition * 1000000) / waveformat->nSamplesPerSec) - ((position * 1000000) / frequency)), available)) { if (available > 0) { adjustVolume(queueBuffer.get(), available); hr = renderClient->GetBuffer(available, &buffer); CHECK_HR(hr); memcpy(buffer, queueBuffer.get(), bufferSize); hr = renderClient->ReleaseBuffer(available, 0); CHECK_HR(hr); bufferPosition += available; } } else { LOG(INFO, LOG_TAG) << "Failed to get chunk\n"; hr = audioClient->Stop(); CHECK_HR(hr); hr = audioClient->Reset(); CHECK_HR(hr); while (active_ && !stream_->waitForChunk(std::chrono::milliseconds(100))) LOG(INFO, LOG_TAG) << "Waiting for chunk\n"; hr = audioClient->Start(); CHECK_HR(hr); bufferPosition = 0; } } } #pragma warning(pop) HRESULT STDMETHODCALLTYPE AudioSessionEventListener::QueryInterface(REFIID riid, VOID** ppvInterface) { if (IID_IUnknown == riid) { AddRef(); *ppvInterface = (IUnknown*)this; } else if (__uuidof(IAudioSessionEvents) == riid) { AddRef(); *ppvInterface = (IAudioSessionEvents*)this; } else { *ppvInterface = NULL; return E_NOINTERFACE; } return S_OK; } HRESULT STDMETHODCALLTYPE AudioSessionEventListener::OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext) { std::ignore = EventContext; volume_ = NewVolume; muted_ = NewMute; if (NewMute) { LOG(DEBUG, LOG_TAG) << ("MUTE\n"); } else { LOG(DEBUG, LOG_TAG) << "Volume = " << (UINT32)(100 * NewVolume + 0.5) << " percent\n"; } return S_OK; } HRESULT STDMETHODCALLTYPE AudioSessionEventListener::OnStateChanged(AudioSessionState NewState) { char* pszState = "?????"; switch (NewState) { case AudioSessionStateActive: pszState = "active"; break; case AudioSessionStateInactive: pszState = "inactive"; break; } LOG(DEBUG, LOG_TAG) << "New session state = " << pszState << "\n"; return S_OK; } HRESULT STDMETHODCALLTYPE AudioSessionEventListener::OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason) { char* pszReason = "?????"; switch (DisconnectReason) { case DisconnectReasonDeviceRemoval: pszReason = "device removed"; break; case DisconnectReasonServerShutdown: pszReason = "server shut down"; break; case DisconnectReasonFormatChanged: pszReason = "format changed"; break; case DisconnectReasonSessionLogoff: pszReason = "user logged off"; break; case DisconnectReasonSessionDisconnected: pszReason = "session disconnected"; break; case DisconnectReasonExclusiveModeOverride: pszReason = "exclusive-mode override"; break; } LOG(INFO, LOG_TAG) << "Audio session disconnected (reason: " << pszReason << ")"; return S_OK; } HRESULT STDMETHODCALLTYPE AudioEndpointVolumeCallback::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) { if (pNotify == NULL) { return E_INVALIDARG; } if (pNotify->bMuted) { LOG(DEBUG, LOG_TAG) << ("MASTER MUTE\n"); } LOG(DEBUG, LOG_TAG) << "Volume = " << (UINT32)(100 * pNotify->fMasterVolume + 0.5) << " percent\n"; volume_ = pNotify->fMasterVolume; muted_ = pNotify->bMuted; return S_OK; } } // namespace player snapcast-0.28.0/client/player/wasapi_player.hpp000066400000000000000000000112141461051111600215330ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2022 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 WASAPI_PLAYER_HPP #define WASAPI_PLAYER_HPP #pragma warning(push) #pragma warning(disable : 4100) // local headers #include "player.hpp" // 3rd party headers #include #include namespace player { class AudioSessionEventListener : public IAudioSessionEvents { LONG _cRef; float volume_ = 1.f; bool muted_ = false; public: AudioSessionEventListener() : _cRef(1) { } float getVolume() { return volume_; } bool getMuted() { return muted_; } ~AudioSessionEventListener() { } // IUnknown methods -- AddRef, Release, and QueryInterface ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG ulRef = InterlockedDecrement(&_cRef); if (0 == ulRef) { delete this; } return ulRef; } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID** ppvInterface); // Notification methods for audio session events HRESULT STDMETHODCALLTYPE OnDisplayNameChanged(LPCWSTR NewDisplayName, LPCGUID EventContext) { return S_OK; } HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPCWSTR NewIconPath, LPCGUID EventContext) { return S_OK; } HRESULT STDMETHODCALLTYPE OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext); HRESULT STDMETHODCALLTYPE OnChannelVolumeChanged(DWORD ChannelCount, float NewChannelVolumeArray[], DWORD ChangedChannel, LPCGUID EventContext) { return S_OK; } HRESULT STDMETHODCALLTYPE OnGroupingParamChanged(LPCGUID NewGroupingParam, LPCGUID EventContext) { return S_OK; } HRESULT STDMETHODCALLTYPE OnStateChanged(AudioSessionState NewState); HRESULT STDMETHODCALLTYPE OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason); }; class AudioEndpointVolumeCallback : public IAudioEndpointVolumeCallback { LONG _cRef; float volume_ = 1.f; bool muted_ = false; public: AudioEndpointVolumeCallback() : _cRef(1) { } ~AudioEndpointVolumeCallback() { } float getVolume() { return volume_; } bool getMuted() { return muted_; } // IUnknown methods -- AddRef, Release, and QueryInterface ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG ulRef = InterlockedDecrement(&_cRef); if (0 == ulRef) { delete this; } return ulRef; } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID** ppvInterface) { if (IID_IUnknown == riid) { AddRef(); *ppvInterface = (IUnknown*)this; } else if (__uuidof(IAudioEndpointVolumeCallback) == riid) { AddRef(); *ppvInterface = (IAudioEndpointVolumeCallback*)this; } else { *ppvInterface = NULL; return E_NOINTERFACE; } return S_OK; } // Callback method for endpoint-volume-change notifications. HRESULT STDMETHODCALLTYPE OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify); }; static constexpr auto WASAPI = "wasapi"; class WASAPIPlayer : public Player { public: WASAPIPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr stream); virtual ~WASAPIPlayer(); static std::vector pcm_list(); protected: virtual void worker(); virtual bool needsThread() const override { return true; } private: AudioSessionEventListener* audioEventListener_; IAudioEndpointVolume* audioEndpointListener_; AudioEndpointVolumeCallback audioEndpointVolumeCallback_; ClientSettings::SharingMode mode_; }; #pragma warning(pop) } // namespace player #endif snapcast-0.28.0/client/snapclient.1000066400000000000000000000043731461051111600171200ustar00rootroot00000000000000.\"groff -Tascii -man snapclient.1 .TH SNAPCLIENT 1 "June 2020" .SH NAME snapclient - Snapcast client .SH SYNOPSIS \fBsnapclient\fR [\fIOPTION\fR]... .SH DESCRIPTION Snapcast is a multiroom 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 multiroom solution. .br The server's audio input is a named pipe `/tmp/snapfifo`. All data that is fed into this file will be send to the connected clients. One of the most generic ways to use Snapcast is in conjunction with the music player daemon or Mopidy, which can be configured to use a named pipe as audio output. .SS Allowed options: .TP \fB--help\fR produce help message .TP \fB-v, --version\fR show version number .TP \fB-h, --host arg\fR server hostname or ip address .TP \fB-p, --port arg (=1704)\fR server port .TP \fB-i, --instance arg (=1)\fR instance id when running multiple instances on the same host .TP \fB--hostID arg\fR unique host id, default is MAC address .TP \fB-l, --list\fR list PCM devices .TP \fB-s, --soundcard arg (=default)\fR index or name of the pcm device .TP \fB--latency arg (=0)\fR latency of the PCM device .TP \fB--sampleformat arg\fR resample audio stream to :: .TP \fB--player arg (=alsa)\fR alsa|file[:|?] .TP \fB--mixer arg (=software)\fR software|hardware|script|none|?[:] .TP \fB-e, --mstderr\fR send metadata to stderr .TP \fB-d, --daemon [=arg(=-3)]\fR daemonize, optional process priority [-20..19] .TP \fB--user arg\fR the user[:group] to run snapclient as when daemonized .TP \fB--logsink arg\fR log sink [null,system,stdout,stderr,file:] .TP \fB--logfilter arg (=*:info)\fR log filter :[,:]* with tag = * or and level = [trace,debug,info,notice,warning,error,fatal] .SH FILES .TP \fI/etc/default/snapclient\fR the daemon default configuration file .SH "COPYRIGHT" Copyright (C) 2014-2024 Johannes Pohl (snapcast@badaix.de). License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH "SEE ALSO" snapserver(1) snapcast-0.28.0/client/snapclient.cpp000066400000000000000000000426451461051111600175460ustar00rootroot00000000000000/*** This file is part of snapcast Copyright (C) 2014-2024 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 . ***/ // local headers #include "common/popl.hpp" #include "controller.hpp" #ifdef HAS_ALSA #include "player/alsa_player.hpp" #endif #ifdef HAS_PULSE #include "player/pulse_player.hpp" #endif #ifdef HAS_WASAPI #include "player/wasapi_player.hpp" #endif #include "player/file_player.hpp" #ifdef HAS_DAEMON #include "common/daemon.hpp" #endif #include "client_settings.hpp" #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "common/version.hpp" // 3rd party headers #include #include // standard headers #include #ifndef WINDOWS #include #include #endif using namespace std; using namespace popl; using namespace player; using namespace std::chrono_literals; static constexpr auto LOG_TAG = "Snapclient"; PcmDevice getPcmDevice(const std::string& player, const std::string& parameter, const std::string& soundcard) { LOG(DEBUG, LOG_TAG) << "Trying to get PCM device for player: " << player << ", parameter: " << ", card: " << soundcard << "\n"; #if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) vector pcm_devices; #if defined(HAS_ALSA) if (player == player::ALSA) pcm_devices = AlsaPlayer::pcm_list(); #endif #if defined(HAS_PULSE) if (player == player::PULSE) pcm_devices = PulsePlayer::pcm_list(parameter); #endif #if defined(HAS_WASAPI) if (player == player::WASAPI) pcm_devices = WASAPIPlayer::pcm_list(); #endif if (player == player::FILE) return FilePlayer::pcm_list(parameter).front(); try { int soundcardIdx = cpt::stoi(soundcard); for (auto dev : pcm_devices) if (dev.idx == soundcardIdx) return dev; } catch (...) { } for (auto dev : pcm_devices) if (dev.name.find(soundcard) != string::npos) return dev; #endif std::ignore = player; std::ignore = parameter; PcmDevice pcm_device; pcm_device.name = soundcard; return pcm_device; } #ifdef WINDOWS // hack to avoid case destinction in the signal handler #define SIGHUP SIGINT const char* strsignal(int sig) { switch (sig) { case SIGTERM: return "SIGTERM"; case SIGINT: return "SIGINT"; case SIGBREAK: return "SIGBREAK"; case SIGABRT: return "SIGABRT"; default: return "Unhandled"; } } #endif int main(int argc, char** argv) { #ifdef MACOS #pragma message "Warning: the macOS support is experimental and might not be maintained" #endif int exitcode = EXIT_SUCCESS; try { ClientSettings settings; string pcm_device(player::DEFAULT_DEVICE); OptionParser op("Allowed options"); auto helpSwitch = op.add("", "help", "produce help message"); auto groffSwitch = op.add("", "groff", "produce groff message"); auto versionSwitch = op.add("v", "version", "show version number"); op.add>("h", "host", "server hostname or ip address", "", &settings.server.host); op.add>("p", "port", "server port", 1704, &settings.server.port); op.add>("i", "instance", "instance id when running multiple instances on the same host", 1, &settings.instance); op.add>("", "hostID", "unique host id, default is MAC address", "", &settings.host_id); // PCM device specific #if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) auto listSwitch = op.add("l", "list", "list PCM devices"); /*auto soundcardValue =*/op.add>("s", "soundcard", "index or name of the pcm device", pcm_device, &pcm_device); #endif /*auto latencyValue =*/op.add>("", "latency", "latency of the PCM device", 0, &settings.player.latency); #ifdef HAS_SOXR auto sample_format = op.add>("", "sampleformat", "resample audio stream to ::", ""); #endif auto supported_players = Controller::getSupportedPlayerNames(); string supported_players_str; for (const auto& supported_player : supported_players) supported_players_str += (!supported_players_str.empty() ? "|" : "") + supported_player; op.add>("", "player", supported_players_str + "[:|?]", supported_players.front(), &settings.player.player_name); // sharing mode #if defined(HAS_OBOE) || defined(HAS_WASAPI) auto sharing_mode = op.add>("", "sharingmode", "audio mode to use [shared|exclusive]", "shared"); #endif // mixer bool hw_mixer_supported = false; #if defined(HAS_ALSA) hw_mixer_supported = true; #endif std::shared_ptr> mixer_mode; std::string mixers = "software"; if (hw_mixer_supported) mixers += "|hardware"; #ifdef SUPPORTS_VOLUME_SCRIPT mixers += "|script"; #endif mixer_mode = op.add>("", "mixer", mixers + "|none|?[:]", "software"); // daemon settings #ifdef HAS_DAEMON int processPriority(-3); auto daemonOption = op.add>("d", "daemon", "daemonize, optional process priority [-20..19]", processPriority, &processPriority); auto userValue = op.add>("", "user", "the user[:group] to run snapclient as when daemonized"); #endif // logging op.add>("", "logsink", "log sink [null,system,stdout,stderr,file:]", settings.logging.sink, &settings.logging.sink); auto logfilterOption = op.add>( "", "logfilter", "log filter :[,:]* with tag = * or and level = [trace,debug,info,notice,warning,error,fatal]", settings.logging.filter); try { op.parse(argc, argv); } catch (const std::invalid_argument& e) { cerr << "Exception: " << e.what() << std::endl; cout << "\n" << op << "\n"; exit(EXIT_FAILURE); } if (versionSwitch->is_set()) { cout << "snapclient v" << version::code << (!version::rev().empty() ? (" (rev " + version::rev(8) + ")") : ("")) << "\n" << "Copyright (C) 2014-2022 BadAix (snapcast@badaix.de).\n" << "License GPLv3+: GNU GPL version 3 or later .\n" << "This is free software: you are free to change and redistribute it.\n" << "There is NO WARRANTY, to the extent permitted by law.\n\n" << "Written by Johannes M. Pohl and contributors .\n\n"; exit(EXIT_SUCCESS); } settings.player.player_name = utils::string::split_left(settings.player.player_name, ':', settings.player.parameter); #if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) if (listSwitch->is_set()) { try { vector pcm_devices; #if defined(HAS_ALSA) if (settings.player.player_name == player::ALSA) pcm_devices = AlsaPlayer::pcm_list(); #endif #if defined(HAS_PULSE) if (settings.player.player_name == player::PULSE) pcm_devices = PulsePlayer::pcm_list(settings.player.parameter); #endif #if defined(HAS_WASAPI) if (settings.player.player_name == player::WASAPI) pcm_devices = WASAPIPlayer::pcm_list(); #endif #ifdef WINDOWS // Set console code page to UTF-8 so console known how to interpret string data SetConsoleOutputCP(CP_UTF8); // Enable buffering to prevent VS from chopping up UTF-8 byte sequences setvbuf(stdout, nullptr, _IOFBF, 1000); #endif for (const auto& dev : pcm_devices) cout << dev.idx << ": " << dev.name << "\n" << dev.description << "\n\n"; if (pcm_devices.empty()) cout << "No PCM device available for audio backend \"" << settings.player.player_name << "\"\n"; } catch (const std::exception& e) { cout << "Failed to get device list: " << e.what() << "\n"; } exit(EXIT_SUCCESS); } #endif if (helpSwitch->is_set()) { cout << op << "\n"; exit(EXIT_SUCCESS); } if (groffSwitch->is_set()) { GroffOptionPrinter option_printer(&op); cout << option_printer.print(); exit(EXIT_SUCCESS); } settings.logging.filter = logfilterOption->value(); if (logfilterOption->is_set()) { for (size_t n = 1; n < logfilterOption->count(); ++n) settings.logging.filter += "," + logfilterOption->value(n); } if (settings.logging.sink.empty()) { settings.logging.sink = "stdout"; #ifdef HAS_DAEMON if (daemonOption->is_set()) settings.logging.sink = "system"; #endif } AixLog::Filter logfilter; auto filters = utils::string::split(settings.logging.filter, ','); for (const auto& filter : filters) logfilter.add_filter(filter); string logformat = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)"; if (settings.logging.sink.find("file:") != string::npos) { string logfile = settings.logging.sink.substr(settings.logging.sink.find(':') + 1); AixLog::Log::init(logfilter, logfile, logformat); } else if (settings.logging.sink == "stdout") AixLog::Log::init(logfilter, logformat); else if (settings.logging.sink == "stderr") AixLog::Log::init(logfilter, logformat); else if (settings.logging.sink == "system") AixLog::Log::init("snapclient", logfilter); else if (settings.logging.sink == "null") AixLog::Log::init(); else throw SnapException("Invalid log sink: " + settings.logging.sink); #if !defined(HAS_AVAHI) && !defined(HAS_BONJOUR) if (settings.server.host.empty()) throw SnapException("Snapserver host not configured and mDNS not available, please configure with \"--host\"."); #endif #ifdef HAS_DAEMON std::unique_ptr daemon; if (daemonOption->is_set()) { string pidFile = "/var/run/snapclient/pid"; if (settings.instance != 1) pidFile += "." + cpt::to_string(settings.instance); string user; string group; if (userValue->is_set()) { if (userValue->value().empty()) throw std::invalid_argument("user must not be empty"); vector user_group = utils::string::split(userValue->value(), ':'); user = user_group[0]; if (user_group.size() > 1) group = user_group[1]; } daemon = std::make_unique(user, group, pidFile); processPriority = std::min(std::max(-20, processPriority), 19); if (processPriority != 0) setpriority(PRIO_PROCESS, 0, processPriority); LOG(NOTICE, LOG_TAG) << "daemonizing" << std::endl; daemon->daemonize(); LOG(NOTICE, LOG_TAG) << "daemon started" << std::endl; } #endif #ifdef HAS_SOXR if (sample_format->is_set()) { settings.player.sample_format = SampleFormat(sample_format->value()); if (settings.player.sample_format.channels() != 0) throw SnapException("sampleformat channels must be * (= same as the source)"); auto bits = settings.player.sample_format.bits(); if ((bits != 0) && (bits != 16) && (bits != 24) && (bits != 32)) throw SnapException("sampleformat bits must be 16, 24, 32, * (= same as the source)"); } #endif #if defined(HAS_OBOE) || defined(HAS_WASAPI) settings.player.sharing_mode = (sharing_mode->value() == "exclusive") ? ClientSettings::SharingMode::exclusive : ClientSettings::SharingMode::shared; #endif if (settings.player.parameter == "?") { if (settings.player.player_name == player::FILE) { cout << "Options are a comma separated list of:\n" << " \"filename=\" - with = \"stdout\", \"stderr\", \"null\" or a filename\n" << " \"mode=[w|a]\" - w: write (discarding the content), a: append (keeping the content)\n"; } #ifdef HAS_PULSE else if (settings.player.player_name == player::PULSE) { cout << "Options are a comma separated list of:\n" << " \"buffer_time=\" - default 100, min 10\n" << " \"server=\" - default not-set: use the default server\n" << " \"property==\" - can be set multiple times, default 'media.role=music'\n"; } #endif #ifdef HAS_ALSA else if (settings.player.player_name == player::ALSA) { cout << "Options are a comma separated list of:\n" << " \"buffer_time=\" - default 80, min 10\n" << " \"fragments=\" - default 4, min 2\n"; } #endif else { cout << "No options available for \"" << settings.player.player_name << "\n"; } exit(EXIT_SUCCESS); } settings.player.pcm_device = getPcmDevice(settings.player.player_name, settings.player.parameter, pcm_device); #if defined(HAS_ALSA) if (settings.player.pcm_device.idx == -1) { LOG(ERROR, LOG_TAG) << "PCM device \"" << pcm_device << "\" not found\n"; // exit(EXIT_FAILURE); } #endif string mode = utils::string::split_left(mixer_mode->value(), ':', settings.player.mixer.parameter); if (mode == "software") settings.player.mixer.mode = ClientSettings::Mixer::Mode::software; else if ((mode == "hardware") && hw_mixer_supported) settings.player.mixer.mode = ClientSettings::Mixer::Mode::hardware; #ifdef SUPPORTS_VOLUME_SCRIPT else if (mode == "script") settings.player.mixer.mode = ClientSettings::Mixer::Mode::script; #endif else if (mode == "none") settings.player.mixer.mode = ClientSettings::Mixer::Mode::none; else if ((mode == "?") || (mode == "help")) { cout << "mixer can be one of 'software', " << (hw_mixer_supported ? "'hardware', " : "") #ifdef SUPPORTS_VOLUME_SCRIPT << "'script', " #endif << "'none'\n" << "followed by optional parameters:\n" << " * software[:poly[:]|exp[:]]\n" << (hw_mixer_supported ? " * hardware[:]\n" : "") #ifdef SUPPORTS_VOLUME_SCRIPT << " * script[: