Repository: Spotifyd/spotifyd Branch: master Commit: 6af1e48d9fe4 Files: 49 Total size: 254.3 KB Directory structure: gitextract_nj0c9tlv/ ├── .all-contributorsrc ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug-report.md │ │ ├── config.yml │ │ └── feature_request.md │ └── workflows/ │ ├── cd.yml │ ├── ci.yml │ └── docs.yml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── CONTRIBUTORS.md ├── Cargo.toml ├── Cross.toml ├── LICENSE ├── README.md ├── contrib/ │ ├── spotifyd.conf │ └── spotifyd.service ├── docs/ │ ├── .gitignore │ ├── book.toml │ └── src/ │ ├── Introduction.md │ ├── SUMMARY.md │ ├── advanced/ │ │ ├── README.md │ │ ├── dbus.md │ │ ├── hooks.md │ │ ├── launchd.md │ │ ├── mpris.md │ │ └── systemd.md │ ├── configuration/ │ │ ├── README.md │ │ ├── audio.md │ │ ├── auth.md │ │ └── other.md │ ├── installation/ │ │ ├── README.md │ │ ├── cross-compilation.md │ │ ├── service.md │ │ └── source.md │ └── troubleshooting.md ├── hooks/ │ └── pre-commit ├── setup-dev-workspace.sh └── src/ ├── alsa_mixer.rs ├── config.rs ├── dbus_mpris.rs ├── error.rs ├── main.rs ├── main_loop.rs ├── no_mixer.rs ├── oauth.rs ├── process.rs ├── setup.rs └── utils.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .all-contributorsrc ================================================ { "projectName": "spotifyd", "projectOwner": "Spotifyd", "repoType": "github", "repoHost": "https://github.com", "files": [ "CONTRIBUTORS.md", "README.md" ], "imageSize": 100, "commit": true, "commitConvention": "angular", "contributors": [ { "login": "SirWindfield", "name": "SirWindfield", "avatar_url": "https://avatars.githubusercontent.com/u/5113257?v=4", "profile": "https://github.com/SirWindfield", "contributions": [ "code", "doc", "infra", "maintenance" ] }, { "login": "0jdxt", "name": "0jdxt", "avatar_url": "https://avatars.githubusercontent.com/u/4650251?v=4", "profile": "https://github.com/0jdxt", "contributions": [ "code", "doc" ] }, { "login": "bcmyers", "name": "Brian Myers", "avatar_url": "https://avatars.githubusercontent.com/u/10109972?v=4", "profile": "https://github.com/bcmyers", "contributions": [ "code", "doc" ] }, { "login": "robinvd", "name": "Robin", "avatar_url": "https://avatars.githubusercontent.com/u/22073483?v=4", "profile": "https://github.com/robinvd", "contributions": [ "code", "doc", "infra", "maintenance" ] }, { "login": "slondr", "name": "Eric S. Londres", "avatar_url": "https://avatars.githubusercontent.com/u/13040688?v=4", "profile": "https://github.com/slondr", "contributions": [ "code", "doc", "infra", "maintenance" ] }, { "login": "mh84", "name": "MH", "avatar_url": "https://avatars.githubusercontent.com/u/17948500?v=4", "profile": "https://github.com/mh84", "contributions": [ "code", "infra" ] }, { "login": "valir", "name": "Valentin Rusu", "avatar_url": "https://avatars.githubusercontent.com/u/4358494?v=4", "profile": "https://github.com/valir", "contributions": [ "code", "doc" ] }, { "login": "Mitschmaster", "name": "Mitschmaster", "avatar_url": "https://avatars.githubusercontent.com/u/39187239?v=4", "profile": "https://github.com/Mitschmaster", "contributions": [ "code", "infra" ] }, { "login": "zv0n", "name": "zv0n", "avatar_url": "https://avatars.githubusercontent.com/u/17143863?v=4", "profile": "https://github.com/zv0n", "contributions": [ "code" ] }, { "login": "Yarn", "name": "Ryan", "avatar_url": "https://avatars.githubusercontent.com/u/908816?v=4", "profile": "https://github.com/Yarn", "contributions": [ "code", "infra" ] }, { "login": "tommady", "name": "tommady", "avatar_url": "https://avatars.githubusercontent.com/u/11532828?v=4", "profile": "https://tommady.com/", "contributions": [ "code" ] }, { "login": "newpavlov", "name": "Artyom Pavlov", "avatar_url": "https://avatars.githubusercontent.com/u/329626?v=4", "profile": "https://github.com/newpavlov", "contributions": [ "code" ] }, { "login": "popey", "name": "Alan Pope", "avatar_url": "https://avatars.githubusercontent.com/u/1841272?v=4", "profile": "http://popey.com/", "contributions": [ "platform" ] }, { "login": "pfrenssen", "name": "Pieter Frenssen", "avatar_url": "https://avatars.githubusercontent.com/u/442924?v=4", "profile": "https://github.com/pfrenssen", "contributions": [ "code" ] }, { "login": "pstruschka", "name": "Peter Son Struschka", "avatar_url": "https://avatars.githubusercontent.com/u/10444945?v=4", "profile": "https://github.com/pstruschka", "contributions": [ "code" ] }, { "login": "nicokaiser", "name": "Nico Kaiser", "avatar_url": "https://avatars.githubusercontent.com/u/238631?v=4", "profile": "https://kaiser.me/", "contributions": [ "infra" ] }, { "login": "JojiiOfficial", "name": "JojiiOfficial", "avatar_url": "https://avatars.githubusercontent.com/u/15957865?v=4", "profile": "https://github.com/JojiiOfficial", "contributions": [ "maintenance" ] }, { "login": "nkitan", "name": "Ankit Das", "avatar_url": "https://avatars.githubusercontent.com/u/32483252?v=4", "profile": "https://github.com/nkitan", "contributions": [ "code" ] }, { "login": "joelpet", "name": "Joel Pettersson", "avatar_url": "https://avatars.githubusercontent.com/u/114321?v=4", "profile": "https://github.com/joelpet", "contributions": [ "doc" ] }, { "login": "juliangaal", "name": "Julian Gaal", "avatar_url": "https://avatars.githubusercontent.com/u/22290570?v=4", "profile": "https://github.com/juliangaal", "contributions": [ "doc", "code" ] }, { "login": "jackloughran", "name": "Jack", "avatar_url": "https://avatars.githubusercontent.com/u/30052269?v=4", "profile": "https://github.com/jackloughran", "contributions": [ "code", "doc" ] }, { "login": "basvandenbrink", "name": "Bas van den Brink", "avatar_url": "https://avatars.githubusercontent.com/u/2811984?v=4", "profile": "https://github.com/basvandenbrink", "contributions": [ "code" ] }, { "login": "eisnerd", "name": "David Eisner", "avatar_url": "https://avatars.githubusercontent.com/u/441072?v=4", "profile": "http://pph.me/david.eisner", "contributions": [ "code" ] }, { "login": "stsydow", "name": "Stefan Sydow", "avatar_url": "https://avatars.githubusercontent.com/u/961256?v=4", "profile": "http://metafly.info/", "contributions": [ "code" ] }, { "login": "TimotheeGerber", "name": "Timothée Gerber", "avatar_url": "https://avatars.githubusercontent.com/u/37541513?v=4", "profile": "https://github.com/TimotheeGerber", "contributions": [ "doc" ] }, { "login": "maringuu", "name": "Marten Ringwelski", "avatar_url": "https://avatars.githubusercontent.com/u/60553448?v=4", "profile": "https://github.com/maringuu", "contributions": [ "code" ] }, { "login": "bertptrs", "name": "Bert Peters", "avatar_url": "https://avatars.githubusercontent.com/u/861864?v=4", "profile": "https://bertptrs.nl/", "contributions": [ "code" ] }, { "login": "Calinou", "name": "Hugo Locurcio", "avatar_url": "https://avatars.githubusercontent.com/u/180032?v=4", "profile": "https://hugo.pro/", "contributions": [ "doc" ] }, { "login": "lulis", "name": "Luiz Bettoni", "avatar_url": "https://avatars.githubusercontent.com/u/6931166?v=4", "profile": "http://odois.org/", "contributions": [ "code" ] }, { "login": "dcoppa", "name": "dcoppa", "avatar_url": "https://avatars.githubusercontent.com/u/1073526?v=4", "profile": "https://github.com/dcoppa", "contributions": [ "code" ] }, { "login": "andir", "name": "Andreas Rammhold", "avatar_url": "https://avatars.githubusercontent.com/u/638836?v=4", "profile": "https://andreas.rammhold.de/", "contributions": [ "code" ] }, { "login": "jenting", "name": "JenTing Hsiao", "avatar_url": "https://avatars.githubusercontent.com/u/49380831?v=4", "profile": "https://github.com/jenting", "contributions": [ "code" ] }, { "login": "PontusPersson", "name": "Pontus Persson", "avatar_url": "https://avatars.githubusercontent.com/u/720546?v=4", "profile": "https://pontus-persson.se/", "contributions": [ "code" ] }, { "login": "Jalle19", "name": "Sam Stenvall", "avatar_url": "https://avatars.githubusercontent.com/u/1106133?v=4", "profile": "https://github.com/Jalle19", "contributions": [ "code" ] }, { "login": "ashleytqy", "name": "ashley teoh", "avatar_url": "https://avatars.githubusercontent.com/u/11889765?v=4", "profile": "https://ashleytqy.github.io/", "contributions": [ "doc" ] }, { "login": "aksel", "name": "aksel", "avatar_url": "https://avatars.githubusercontent.com/u/6985716?v=4", "profile": "https://github.com/aksel", "contributions": [ "code" ] }, { "login": "sk22", "name": "Samuel Kaiser", "avatar_url": "https://avatars.githubusercontent.com/u/6217438?v=4", "profile": "https://sk22.ml/", "contributions": [ "doc" ] }, { "login": "smgt", "name": "Simon Gate", "avatar_url": "https://avatars.githubusercontent.com/u/2408?v=4", "profile": "http://smgt.me/", "contributions": [ "code" ] }, { "login": "mattbailey", "name": "Matt Bailey", "avatar_url": "https://avatars.githubusercontent.com/u/216331?v=4", "profile": "http://mdb.io/", "contributions": [ "doc" ] }, { "login": "sflip", "name": "Philipp Moers", "avatar_url": "https://avatars.githubusercontent.com/u/6862899?v=4", "profile": "https://philippmoers.de/", "contributions": [ "code", "doc" ] }, { "login": "Mange", "name": "Magnus Bergmark", "avatar_url": "https://avatars.githubusercontent.com/u/1599?v=4", "profile": "https://github.com/Mange", "contributions": [ "code" ] }, { "login": "Rik-de-Kort", "name": "Rik-de-Kort", "avatar_url": "https://avatars.githubusercontent.com/u/32839123?v=4", "profile": "https://github.com/Rik-de-Kort", "contributions": [ "doc" ] }, { "login": "vringar", "name": "Stefan Zabka", "avatar_url": "https://avatars.githubusercontent.com/u/13276717?v=4", "profile": "https://github.com/vringar", "contributions": [ "doc" ] }, { "login": "reschandreas", "name": "Andreas Resch", "avatar_url": "https://avatars.githubusercontent.com/u/16179620?v=4", "profile": "https://github.com/reschandreas", "contributions": [ "code" ] }, { "login": "marijnvanderhorst", "name": "Marijn van der Horst", "avatar_url": "https://avatars.githubusercontent.com/u/7057618?v=4", "profile": "https://github.com/marijnvanderhorst", "contributions": [ "code" ] }, { "login": "Jason-Cooke", "name": "Jason Cooke", "avatar_url": "https://avatars.githubusercontent.com/u/5185660?v=4", "profile": "https://twitter.com/JSON_C11", "contributions": [ "doc" ] }, { "login": "codyshepherd", "name": "Cody Shepherd", "avatar_url": "https://avatars.githubusercontent.com/u/15008379?v=4", "profile": "https://launchpad.net/~codyshepherd", "contributions": [ "code" ] }, { "login": "bobvanderlinden", "name": "Bob van der Linden", "avatar_url": "https://avatars.githubusercontent.com/u/6375609?v=4", "profile": "https://github.com/bobvanderlinden", "contributions": [ "code" ] }, { "login": "pyrho", "name": "Damien Rajon", "avatar_url": "https://avatars.githubusercontent.com/u/145502?v=4", "profile": "https://www.25.wf/", "contributions": [ "code" ] }, { "login": "awerlang", "name": "André Werlang", "avatar_url": "https://avatars.githubusercontent.com/u/589286?v=4", "profile": "http://blog.werlangtecnologia.com.br/", "contributions": [ "infra" ] }, { "login": "timotk", "name": "Timo", "avatar_url": "https://avatars.githubusercontent.com/u/6358247?v=4", "profile": "https://github.com/timotk", "contributions": [ "doc" ] }, { "login": "dimlev", "name": "dimlev", "avatar_url": "https://avatars.githubusercontent.com/u/1188269?v=4", "profile": "https://github.com/dimlev", "contributions": [ "doc" ] }, { "login": "stuarth", "name": "Stuart Hinson", "avatar_url": "https://avatars.githubusercontent.com/u/7055?v=4", "profile": "http://stuarth.github.io/", "contributions": [ "code" ] }, { "login": "bphermansson", "name": "Patrik Hermansson", "avatar_url": "https://avatars.githubusercontent.com/u/3775861?v=4", "profile": "http://www.patrikhermansson.se/", "contributions": [ "doc" ] }, { "login": "qaisjp", "name": "Qais Patankar", "avatar_url": "https://avatars.githubusercontent.com/u/923242?v=4", "profile": "https://qaisjp.com/", "contributions": [ "doc" ] }, { "login": "backspac", "name": "backspac", "avatar_url": "https://avatars.githubusercontent.com/u/8981640?v=4", "profile": "https://github.com/backspac", "contributions": [ "code" ] }, { "login": "WhyNotHugo", "name": "Hugo Barrera", "avatar_url": "https://avatars.githubusercontent.com/u/730811?v=4", "profile": "https://hugo.barrera.io/", "contributions": [ "platform" ] }, { "login": "0xflotus", "name": "0xflotus", "avatar_url": "https://avatars.githubusercontent.com/u/26602940?v=4", "profile": "https://github.com/0xflotus", "contributions": [ "doc" ] }, { "login": "wvangeit", "name": "Werner Van Geit", "avatar_url": "https://avatars.githubusercontent.com/u/3098670?v=4", "profile": "https://github.com/wvangeit", "contributions": [ "code" ] }, { "login": "ghishadow", "name": "Suraj Ghimire", "avatar_url": "https://avatars.githubusercontent.com/u/9583775?v=4", "profile": "https://github.com/ghishadow", "contributions": [ "doc" ] }, { "login": "TobiMichael96", "name": "Tobias Michael Effner", "avatar_url": "https://avatars.githubusercontent.com/u/43846093?v=4", "profile": "https://github.com/TobiMichael96", "contributions": [ "code" ] }, { "login": "johnalanwoods", "name": "Woodstock", "avatar_url": "https://avatars.githubusercontent.com/u/5158898?v=4", "profile": "https://github.com/johnalanwoods", "contributions": [ "doc" ] }, { "login": "ah-", "name": "Andreas Heider", "avatar_url": "https://avatars.githubusercontent.com/u/1349849?v=4", "profile": "https://github.com/ah-", "contributions": [ "code" ] }, { "login": "nickcorona", "name": "Nick Corona", "avatar_url": "https://avatars.githubusercontent.com/u/7490453?v=4", "profile": "https://github.com/nickcorona", "contributions": [ "doc" ] }, { "login": "vickychenglau", "name": "Vicky C Lau", "avatar_url": "https://avatars.githubusercontent.com/u/22065437?v=4", "profile": "https://github.com/vickychenglau", "contributions": [ "doc" ] }, { "login": "christopher-dG", "name": "Chris de Graaf", "avatar_url": "https://avatars.githubusercontent.com/u/17228795?v=4", "profile": "https://github.com/christopher-dG", "contributions": [ "code" ] }, { "login": "justin-gerhardt", "name": "Justin Gerhardt", "avatar_url": "https://avatars.githubusercontent.com/u/6844979?v=4", "profile": "https://github.com/justin-gerhardt", "contributions": [ "code" ] }, { "login": "wdehoog", "name": "Willem-Jan de Hoog", "avatar_url": "https://avatars.githubusercontent.com/u/3353303?v=4", "profile": "https://github.com/wdehoog", "contributions": [ "code" ] }, { "login": "CPerezz", "name": "Carlos Pérez", "avatar_url": "https://avatars.githubusercontent.com/u/37264926?v=4", "profile": "https://github.com/CPerezz", "contributions": [ "doc" ] }, { "login": "RlndVt", "name": "Roland Vet", "avatar_url": "https://avatars.githubusercontent.com/u/1658570?v=4", "profile": "https://github.com/RlndVt", "contributions": [ "doc" ] }, { "login": "Plecra", "name": "Plecra", "avatar_url": "https://avatars.githubusercontent.com/u/60934058?v=4", "profile": "https://github.com/Plecra", "contributions": [ "maintenance" ] }, { "login": "marcelbuesing", "name": "Marcel", "avatar_url": "https://avatars.githubusercontent.com/u/5637837?v=4", "profile": "https://github.com/marcelbuesing", "contributions": [ "code", "maintenance" ] }, { "login": "izissise", "name": "Hugues Morisset", "avatar_url": "https://avatars.githubusercontent.com/u/2104672?v=4", "profile": "https://github.com/izissise", "contributions": [ "code" ] }, { "login": "katrielalex", "name": "Katriel Cohn-Gordon", "avatar_url": "https://avatars.githubusercontent.com/u/315959?v=4", "profile": "http://www.katriel.co.uk/", "contributions": [ "doc" ] }, { "login": "jb55", "name": "William Casarin", "avatar_url": "https://avatars.githubusercontent.com/u/45598?v=4", "profile": "https://github.com/jb55", "contributions": [ "code" ] }, { "login": "Gorzen", "name": "Lucien Iseli", "avatar_url": "https://avatars.githubusercontent.com/u/28461464?v=4", "profile": "https://github.com/Gorzen", "contributions": [ "doc" ] }, { "login": "schnitzeltony", "name": "Andreas Müller", "avatar_url": "https://avatars.githubusercontent.com/u/2571823?v=4", "profile": "https://github.com/schnitzeltony", "contributions": [ "doc" ] }, { "login": "Crazybus", "name": "Michael Russell", "avatar_url": "https://avatars.githubusercontent.com/u/4550136?v=4", "profile": "https://michaelrussell.ninja/", "contributions": [ "code" ] }, { "login": "metiis", "name": "Julia", "avatar_url": "https://avatars.githubusercontent.com/u/31927016?v=4", "profile": "https://github.com/metiis", "contributions": [ "code" ] }, { "login": "aignas", "name": "Ignas Anikevicius", "avatar_url": "https://avatars.githubusercontent.com/u/240938?v=4", "profile": "http://anikevicius.lt/", "contributions": [ "infra", "doc", "maintenance" ] }, { "login": "Ben-PH", "name": "Ben", "avatar_url": "https://avatars.githubusercontent.com/u/16680090?v=4", "profile": "https://github.com/Ben-PH", "contributions": [ "maintenance" ] }, { "login": "MarinPostma", "name": "marin", "avatar_url": "https://avatars.githubusercontent.com/u/28804882?v=4", "profile": "https://github.com/MarinPostma", "contributions": [ "maintenance" ] }, { "login": "SimonPersson", "name": "Simon Persson", "avatar_url": "https://avatars.githubusercontent.com/u/606973?v=4", "profile": "https://github.com/SimonPersson", "contributions": [ "maintenance", "doc", "code", "infra" ] } ], "contributorsPerLine": 7, "contributorsSortAlphabetically": true } ================================================ FILE: .github/ISSUE_TEMPLATE/bug-report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- **Description** **To Reproduce** **Expected behavior** **Logs**
Click to show logs ``` ```
**Compilation flags** - [ ] dbus_mpris - [x] alsa_backend - [ ] portaudio_backend - [ ] pulseaudio_backend - [ ] rodio_backend **Versions (please complete the following information):** - OS: - Spotifyd: - cargo: ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: General questions and support url: https://matrix.to/#/#spotifyd:matrix.org about: You can also reach us via matrix and ask your questions regarding spotifyd there. - name: Other url: https://github.com/Spotifyd/spotifyd/discussions/new/choose about: For other requests, consider creating a discussion. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: enhancement 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. ================================================ FILE: .github/workflows/cd.yml ================================================ name: Continuous Deployment on: push: branches: - master tags: - 'v*.*.*' jobs: build: name: Building ${{matrix.os}}-${{ matrix.arch }} (${{ matrix.artifact_type }}) runs-on: ${{ matrix.runs_on }} strategy: matrix: os: [macos, linux] arch: [x86_64, aarch64, armv7] rust: [stable] artifact_type: ['slim', 'default', 'full'] # The build strategy will build all types for each OS specified include: # Runner configuration - os: macos arch: x86_64 runs_on: macos-15-intel - os: macos arch: aarch64 runs_on: macos-15 - os: linux runs_on: ubuntu-22.04 - os: linux arch: aarch64 runs_on: ubuntu-22.04-arm # DBus configuration - artifact_type: slim dbus: '' - artifact_type: default dbus: dbus_mpris - artifact_type: full dbus: dbus_mpris # Cross Compilation Targets - os: linux arch: armv7 target: armv7-unknown-linux-gnueabihf # Audio backend configuration: Linux - os: linux artifact_type: slim audio_backends: alsa_backend - os: linux artifact_type: default audio_backends: alsa_backend,pulseaudio_backend,rodio_backend - os: linux artifact_type: full audio_backends: alsa_backend,pulseaudio_backend,rodio_backend,rodiojack_backend # Audio backend configuration: macOS - os: macos audio_backends: portaudio_backend,rodio_backend exclude: - os: macos artifact_type: 'full' - os: macos arch: armv7 steps: - name: Checking out sources uses: actions/checkout@v4 - name: Installing needed macOS dependencies if: matrix.os == 'macos' run: brew install dbus portaudio - name: Installing needed Ubuntu dependencies if: startsWith(matrix.runs_on, 'ubuntu') && matrix.target == '' run: | sudo apt-get update # WORKAROUND: fix aws-lc-sys compiler bug failure sudo apt-get remove -y gcc-9 sudo apt-get install -y gcc-10 echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=gcc-10" >> "$GITHUB_ENV" echo "CC=gcc-10" >> "$GITHUB_ENV" # alsa_backend,rodio_backend and base deps sudo apt-get install -y libasound2-dev libssl-dev # dbus_mpris sudo apt-get install -y libdbus-1-dev # pulseaudio_backend sudo apt-get install -y libpulse-dev # portaudio_backend sudo apt-get install -y portaudio19-dev - name: Determine cargo args run: | features="--no-default-features --features ${{ matrix.dbus }},${{ matrix.audio_backends }}" echo CARGO_ARGS="--locked --release $features" | tee -a "$GITHUB_ENV" - name: Build (using cargo) if: matrix.target == '' run: | cargo +${{ matrix.rust }} build $CARGO_ARGS - name: Build (using cross) if: matrix.target != '' uses: houseabsolute/actions-rust-cross@v1 with: cross-version: baf457e # currently needed (check again if cross version > 0.2.5) command: build toolchain: ${{ matrix.rust }} target: ${{ matrix.target }} args: $CARGO_ARGS - name: Uploading artifacts uses: actions/upload-artifact@v4 with: name: spotifyd-${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.artifact_type }} path: target/${{ matrix.target }}/release/spotifyd release: # only runs when a version tag is pushed if: startsWith(github.ref, 'refs/tags/v') needs: build runs-on: ubuntu-latest steps: - name: Downloading artifacts # download all binaries uses: actions/download-artifact@v4 - name: Packaging final binary shell: bash run: | for artifact_dir in ./*/ do pushd $artifact_dir artifact_name=$(basename $artifact_dir) tar czvf $artifact_name.tar.gz spotifyd shasum -a 512 $artifact_name.tar.gz > $artifact_name.sha512 popd done - name: Releasing assets uses: softprops/action-gh-release@v1 with: files: | **/*.tar.gz **/*.sha512 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/ci.yml ================================================ name: Continuous Integration on: pull_request: paths: - '**.rs' - 'Cargo.toml' - 'Cargo.lock' - 'contrib/spotifyd.conf' jobs: codestyle: runs-on: ubuntu-latest steps: - name: Installing Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable override: true - name: Checking out sources uses: actions/checkout@v1 - name: Installing rustfmt run: rustup component add rustfmt - name: Running rustfmt uses: actions-rs/cargo@v1 with: command: fmt args: -- --check lint: needs: [codestyle] runs-on: ubuntu-latest steps: - name: Installing Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable override: true - name: Installing needed Ubuntu dependencies run: | sudo apt-get update sudo apt-get install -y -qq libasound2-dev libssl-dev libpulse-dev libdbus-1-dev portaudio19-dev - name: Checking out sources uses: actions/checkout@v1 - name: Installing clippy run: rustup component add clippy - name: Linting project uses: actions-rs/cargo@v1 with: command: clippy args: --all-targets --all-features -- -D warnings test: needs: [lint] runs-on: ${{ matrix.os }} strategy: matrix: rust: [stable, 1.88] os: [macos-latest, ubuntu-latest] include: - os: macos-latest features: portaudio_backend,rodio_backend - os: ubuntu-latest features: alsa_backend,rodio_backend,dbus_mpris steps: - name: Installing Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Installing macOS dependencies if: matrix.os == 'macos-latest' run: brew install pkg-config portaudio - name: Installing needed Ubuntu dependencies if: matrix.os == 'ubuntu-latest' run: | sudo apt-get update sudo apt-get install -y -qq libasound2-dev libssl-dev libpulse-dev libdbus-1-dev - name: Checking out sources uses: actions/checkout@v1 - name: Checking Rust code uses: actions-rs/cargo@v1 with: command: test args: --locked --no-default-features --features ${{ matrix.features }} ================================================ FILE: .github/workflows/docs.yml ================================================ name: Continuous Integration - Docs on: # Runs on pushes targeting the default branch push: branches: ["master"] paths: - .github/workflows/docs.yml - docs/** # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. concurrency: group: "pages" cancel-in-progress: false jobs: # Build job build: runs-on: ubuntu-latest env: MDBOOK_VERSION: 0.4.45 steps: - uses: actions/checkout@v4 - name: Install mdBook run: | curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf -y | sh rustup update cargo install --version ${MDBOOK_VERSION} mdbook - name: Setup Pages id: pages uses: actions/configure-pages@v3 - name: Build with mdBook run: mdbook build ./docs - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: path: ./docs/book # Deployment job deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest needs: build steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 ================================================ FILE: .gitignore ================================================ # Created by https://www.gitignore.io/api/vim,rust ### Vim ### # swap [._]*.s[a-v][a-z] [._]*.sw[a-p] [._]s[a-v][a-z] [._]sw[a-p] # session Session.vim # temporary .netrwhist *~ # auto-generated tag files tags ### Rust ### # Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock #Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk # End of https://www.gitignore.io/api/vim,rust *.rustfmt .idea .vscode # Windows logs *.log ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.4.2] ### Fixed - fix multiple playback issues introduced by Spotify changes ([#1362], [#1374]) - fix crash on user switch ([#1361]) ### Added - add suggestions for alsa mixer / control device names - improve distribution support for Debian and Fedora ([#1364], [#1372]) [#1361]: https://github.com/Spotifyd/spotifyd/pull/1361 [#1362]: https://github.com/Spotifyd/spotifyd/pull/1362 [#1364]: https://github.com/Spotifyd/spotifyd/pull/1364 [#1372]: https://github.com/Spotifyd/spotifyd/pull/1372 [#1374]: https://github.com/Spotifyd/spotifyd/pull/1374 ## [0.4.1] ### Fixed - revert default features to `alsa_backend` ([#1337]) - do not require `bindgen` dependencies on supported systems ([#1340]) - always return exitcode 1 on error ([#1338]) - the released binaries for `linux-x86_64` also work for older systems ([#1342]) [#1337]: https://github.com/Spotifyd/spotifyd/pull/1337 [#1338]: https://github.com/Spotifyd/spotifyd/pull/1338 [#1340]: https://github.com/Spotifyd/spotifyd/pull/1340 [#1342]: https://github.com/Spotifyd/spotifyd/pull/1342 ## [0.4.0] ### Breaking - username and password authentaction have been removed and are replaced by OAuth ([#1321]) Look at the [docs](https://docs.spotifyd.rs/) for setup instructions. ### Added - retry enabling discovery several times before exiting ([#1228]) - development artifacts are now available ([#1332]) - prebuilt binaries are available for `aarch64` (both Linux and macOS) ([#1332]) - Windows and Android are now supported ([#1219], [#1314]) - expose pipe and subprocess backends ([#1284]) - new device type options are available ([#1316]) - OAuth login is now supported ([#1321]) - a warning is emitted on unsupported configuration values ([#1327]) ### Changed - the docs have been overhauled to reflect the current state of the project and simplify onboarding ([#1327]) - `librespot` dependency has been updated to 0.6 ([#1317]) - Credential caching has been re-enabled. ([#1214]) ### Fixed - alsa mixer: volume calculation has been fixed ([#1229]) ### Removed - `armv6` binaries are no longer available by default ([#1332]) If you still need them, please join our matrix channel (https://matrix.to/#/#spotifyd:matrix.org) and tell us! [#1214]: https://github.com/Spotifyd/spotifyd/pull/1214 [#1229]: https://github.com/Spotifyd/spotifyd/pull/1229 [#1228]: https://github.com/Spotifyd/spotifyd/pull/1228 [#1284]: https://github.com/Spotifyd/spotifyd/pull/1284 [#1219]: https://github.com/Spotifyd/spotifyd/pull/1219 [#1314]: https://github.com/Spotifyd/spotifyd/pull/1314 [#1316]: https://github.com/Spotifyd/spotifyd/pull/1316 [#1317]: https://github.com/Spotifyd/spotifyd/pull/1317 [#1321]: https://github.com/Spotifyd/spotifyd/pull/1321 [#1327]: https://github.com/Spotifyd/spotifyd/pull/1327 [#1332]: https://github.com/Spotifyd/spotifyd/pull/1332 ## [0.3.5] We now have a [project website](https://spotifyd.rs) (thanks @slondr!) and a [matrix room](https://matrix.to/#/#spotifyd:matrix.org). Feel free to join and ask your questions! ### Added - `TransferPlayback` D-Bus method to transfer the playback to `spotifyd` ([#1162]) To host this, a `rs.spotifyd.Controls` interface has been added. - A `audio_format` option was added to circumvent certain errors ([#1082]) - A setter was added to the `Shuffle` property ([#1188]) - `volume_control = "none"` variant to disable changing the volume in clients ([#750]) ### Changed - Improve backend selection logic, especially for macOS ([#1158]) - Update `keyring` dependency to newest version ([#1174]) - `VolumeUp`, `VolumeDown` D-Bus methods have been copied to spotifyd's controls interface ([#1162]) Their versions in `org.mpris.MediaPlayer2.Player` have been deprecated and will be removed in a breaking release. - The `librespot` dependency has been upgraded to the most recent release 🎉 ([#1182], [#1197]) - Many other dependency updates ([#1183], [#1145], [#1199]) - Documentation improvements ([#1156]) - Our minimum supported rust version (MSRV) has been bumped to 1.64 ([#1145]) [#750]: https://github.com/Spotifyd/spotifyd/pull/750 [#1082]: https://github.com/Spotifyd/spotifyd/pull/1082 [#1145]: https://github.com/Spotifyd/spotifyd/pull/1145 [#1156]: https://github.com/Spotifyd/spotifyd/pull/1156 [#1158]: https://github.com/Spotifyd/spotifyd/pull/1158 [#1162]: https://github.com/Spotifyd/spotifyd/pull/1162 [#1174]: https://github.com/Spotifyd/spotifyd/pull/1174 [#1182]: https://github.com/Spotifyd/spotifyd/pull/1182 [#1183]: https://github.com/Spotifyd/spotifyd/pull/1183 [#1188]: https://github.com/Spotifyd/spotifyd/pull/1188 [#1197]: https://github.com/Spotifyd/spotifyd/pull/1197 [#1199]: https://github.com/Spotifyd/spotifyd/pull/1199 ## [0.3.4] ### Added - Implement the `PropertiesChanged` and `Seeked` events for the MPRIS-interface ([#1025]) - Add `cache_size` configuration option ([#1092]) - Add `dbus_type` configuration option ([#954]) - Added formal documentation of the minimum required Rust version - which is currently 1.62 ([#1127]) ### Changed - Improvements to the documentation ([#894], [#955], [#1030], [#1039], [#1054], [#1055], [#1067]) - Fix cumulating delay in `on_song_change_hook` ([#1059]) - Only enable one of zeroconf discovery and password-authentication at the same time ([#1059]) - Convert mainloop to using `async` / `await` ([#1059]) - Upgrade `rspotify` dependency to `0.11.5` ([#1079]) - Improve error reporting ([#1108]) - Make `spotifyd` bus name unique ([#1100]) **Note:** If you were relying on the consistent bus name of `org.mpris.MediaPlayer2.spotifyd`, you can adapt your script e.g. by querying the name like `qdbus | grep "org.mpris.MediaPlayer2.spotifyd"` - Fix wrong handling of credential cache ([#1121]) ### Removed - Replace redundant `reqwest` dependency ([#1120]) [#894]: https://github.com/Spotifyd/spotifyd/pull/894 [#954]: https://github.com/Spotifyd/spotifyd/pull/954 [#955]: https://github.com/Spotifyd/spotifyd/pull/955 [#1025]: https://github.com/Spotifyd/spotifyd/pull/1025 [#1030]: https://github.com/Spotifyd/spotifyd/pull/1030 [#1039]: https://github.com/Spotifyd/spotifyd/pull/1039 [#1054]: https://github.com/Spotifyd/spotifyd/pull/1054 [#1055]: https://github.com/Spotifyd/spotifyd/pull/1055 [#1059]: https://github.com/Spotifyd/spotifyd/pull/1059 [#1067]: https://github.com/Spotifyd/spotifyd/pull/1067 [#1079]: https://github.com/Spotifyd/spotifyd/pull/1079 [#1092]: https://github.com/Spotifyd/spotifyd/pull/1092 [#1100]: https://github.com/Spotifyd/spotifyd/pull/1100 [#1108]: https://github.com/Spotifyd/spotifyd/pull/1108 [#1120]: https://github.com/Spotifyd/spotifyd/pull/1120 [#1121]: https://github.com/Spotifyd/spotifyd/pull/1120 ## [0.3.3] ### Added - Add `debug_credentials` feature for debugging `BadCredentials` errors [#915] - Implement `VolumeUp` and `VolumeDown` in the DBUS/MPRIS interface [#963] - Update librespot to 0.2.0 [#977] - Rewrite DBUS/MPRIS integration [#977] ### Changed - Improved panic error message [#925] ### Removed [#915]: https://github.com/Spotifyd/spotifyd/pull/915 [#925]: https://github.com/Spotifyd/spotifyd/pull/925 [#963]: https://github.com/Spotifyd/spotifyd/pull/963 [#977]: https://github.com/Spotifyd/spotifyd/pull/977 ## [0.3.1] ### Added - Use eyre for better error reporting [#789] - Add a contributers file ### Changed - Change docs from readme to mkdocs [#783] - Update librespot, thus fixing [#719] [#900] ### Removed [#789]: https://github.com/Spotifyd/spotifyd/pull/789 [#783]: https://github.com/Spotifyd/spotifyd/pull/783 [#719]: https://github.com/Spotifyd/spotifyd/issues/719 [#900]: https://github.com/Spotifyd/spotifyd/pull/900 ## [0.3.0] ### Added - Added a changelog [#714] ### Changed - Changed the config format from ini to TOML [#571] [#571]: https://github.com/Spotifyd/spotifyd/pull/571 [#714]: https://github.com/Spotifyd/spotifyd/pull/714 ### Removed ## [0.2.24] [Unreleased]: https://github.com/Spotifyd/spotifyd/compare/v0.4.2...HEAD [0.4.2]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.4.2 [0.4.1]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.4.1 [0.4.0]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.4.0 [0.3.5]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.5 [0.3.4]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.4 [0.3.3]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.3 [0.3.1]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.1 [0.3.0]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.0 [0.2.24]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.2.24 ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing ## Setup __Important:__ Make sure to install the provided git hooks by running `setup-dev-workspace.sh`! ### Install Rust It is recommended to install rust through [rustup](https://rustup.rs). System package managers often have outdated versions of Rust or don't include rustfmt/clippy. ### Install rustfmt and clippy ```sh rustup component add rustfmt rustup component add clippy ``` ### External Dependencies The rodio backend requires alsa development libraries on linux. These should be available through your package manager. No extra dependencies should be needed on macOS/Windows. Other backends will need additional dependencies. Some are documented in the (readme)[https://github.com/Spotifyd/spotifyd/blob/master/README.md] and the (librespot repo)[https://github.com/librespot-org/librespot/blob/dev/CONTRIBUTING.md]. ## Building and Running the project To run spotifyd with the rodio backend run ```sh cargo run --features rodio_backend --no-default-features -- --backend rodio --no-daemon ``` See the readme for information on setting up a config file and what features are available. ## Contributing Code Note that spotifyd uses `Cargo.lock` to track dependency versions. It shouldn't be changed unless you are intentionally bumping a dependency version. Check your code with `rustfmt` and `clippy`. ```sh cargo fmt -- --check cargo clippy --no-default-features --features rodio_backend -- -D warnings ``` CI will run `clippy --all-targets --all-features -- -D warnings` but this requires having dependencies for all features installed. Create a PR on github. ================================================ FILE: CONTRIBUTORS.md ================================================ ## Contributors ✨ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

0jdxt

💻 📖

0xflotus

📖

Alan Pope

📦

Andreas Heider

💻

Andreas Müller

📖

Andreas Rammhold

💻

Andreas Resch

💻

André Werlang

🚇

Ankit Das

💻

Artyom Pavlov

💻

Bas van den Brink

💻

Ben

🚧

Bert Peters

💻

Bob van der Linden

💻

Brian Myers

💻 📖

Carlos Pérez

📖

Chris de Graaf

💻

Cody Shepherd

💻

Damien Rajon

💻

David Eisner

💻

Eric S. Londres

💻 📖 🚇 🚧

Hugo Barrera

📦

Hugo Locurcio

📖

Hugues Morisset

💻

Ignas Anikevicius

🚇 📖 🚧

Jack

💻 📖

Jason Cooke

📖

JenTing Hsiao

💻

Joel Pettersson

📖

JojiiOfficial

🚧

Julia

💻

Julian Gaal

📖 💻

Justin Gerhardt

💻

Katriel Cohn-Gordon

📖

Lucien Iseli

📖

Luiz Bettoni

💻

MH

💻 🚇

Magnus Bergmark

💻

Marcel

💻 🚧

Marijn van der Horst

💻

Marten Ringwelski

💻

Matt Bailey

📖

Michael Russell

💻

Mitschmaster

💻 🚇

Nick Corona

📖

Nico Kaiser

🚇

Patrik Hermansson

📖

Peter Son Struschka

💻

Philipp Moers

💻 📖

Pieter Frenssen

💻

Plecra

🚧

Pontus Persson

💻

Qais Patankar

📖

Rik-de-Kort

📖

Robin

💻 📖 🚇 🚧

Roland Vet

📖

Ryan

💻 🚇

Sam Stenvall

💻

Samuel Kaiser

📖

Simon Gate

💻

Simon Persson

🚧 📖 💻 🚇

SirWindfield

💻 📖 🚇 🚧

Stefan Sydow

💻

Stefan Zabka

📖

Stuart Hinson

💻

Suraj Ghimire

📖

Timo

📖

Timothée Gerber

📖

Tobias Michael Effner

💻

Valentin Rusu

💻 📖

Vicky C Lau

📖

Werner Van Geit

💻

Willem-Jan de Hoog

💻

William Casarin

💻

Woodstock

📖

aksel

💻

ashley teoh

📖

backspac

💻

dcoppa

💻

dimlev

📖

marin

🚧

tommady

💻

zv0n

💻

sckova

💻
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! ================================================ FILE: Cargo.toml ================================================ [package] authors = ["Simon Persson ", "Sven Lechner ", "eladyn "] edition = "2024" name = "spotifyd" description = "A Spotify daemon" repository = "https://github.com/Spotifyd/spotifyd" license = "GPL-3.0-only" version = "0.4.2" resolver = "2" rust-version = "1.88" [dependencies] alsa = { version = "0.10.0", optional = true } chrono = "0.4" dbus = { version = "0.9", optional = true } dbus-tokio = { version = "0.7.3", optional = true } dbus-crossroads = { version = "0.5.0", optional = true } fern = { version = "0.7.0", features = ["syslog-7", "colored"] } futures = "0.3.15" gethostname = "1.0.0" hex = "0.4" libc = "0.2.82" log = "0.4.6" serde = { version = "1.0.115", features = ["derive"] } sha-1 = "0.10" tokio = {version = "1.44.2", features = ["signal", "rt-multi-thread", "process", "io-std"] } tokio-stream = "0.1.7" url = "2.2.2" librespot-audio = { version = "0.8.0", default-features = false } librespot-playback = { version = "0.8.0", default-features = false } librespot-core = "0.8.0" librespot-discovery = "0.8.0" librespot-connect = "0.8.0" librespot-metadata = "0.8.0" librespot-protocol = "0.8.0" librespot-oauth = "0.8.0" toml = "0.9.8" color-eyre = "0.6" directories = "6.0.0" thiserror = "2.0" time = { version = "0.3.47", default-features = false, features = ["formatting"] } clap = { version = "4.5.23", features = ["derive"] } serde_ignored = "0.1.10" [target.'cfg(unix)'.dependencies] daemonize = "0.5" syslog = "7" [target.'cfg(target_os = "macos")'.dependencies] whoami = "1" [target.'cfg(target_os = "openbsd")'.dependencies] pledge = "0.4.2" [target.'cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))'.dependencies] aws-lc-rs = { version = "1.12.6", features = ["bindgen"] } [dev-dependencies] env_logger = "0.11" [features] alsa_backend = ["librespot-playback/alsa-backend", "dep:alsa"] dbus_mpris = ["dep:dbus", "dep:dbus-tokio", "dep:dbus-crossroads"] default = ["alsa_backend", "pulseaudio_backend", "dbus_mpris"] portaudio_backend = ["librespot-playback/portaudio-backend"] pulseaudio_backend = ["librespot-playback/pulseaudio-backend"] rodio_backend = ["librespot-playback/rodio-backend"] rodiojack_backend = ["librespot-playback/rodiojack-backend"] [package.metadata.deb] depends = "$auto" features = ["pulseaudio_backend", "dbus_mpris"] assets = [ ["target/release/spotifyd", "usr/bin/", "755"], ["README.md", "usr/share/doc/spotifyd/README", "644"], ["contrib/spotifyd.service", "etc/systemd/user/", "644"], ] [package.metadata.generate-rpm] assets = [ { source = "target/release/spotifyd", dest = "/usr/bin/spotifyd", mode = "755" }, { source = "README.md", dest = "/usr/share/doc/spotifyd/README", mode = "644" }, { source = "contrib/spotifyd.service", dest = "/etc/systemd/user/spotifyd.service", mode = "644" }, ] [profile.release] lto = true ##### uncomment to test the newest librespot git version # [patch.crates-io] # librespot-audio = { git = "https://github.com/librespot-org/librespot" } # librespot-playback = { git = "https://github.com/librespot-org/librespot" } # librespot-core = { git = "https://github.com/librespot-org/librespot" } # librespot-discovery = { git = "https://github.com/librespot-org/librespot" } # librespot-connect = { git = "https://github.com/librespot-org/librespot" } # librespot-metadata = { git = "https://github.com/librespot-org/librespot" } # librespot-protocol = { git = "https://github.com/librespot-org/librespot" } # librespot-oauth = { git = "https://github.com/librespot-org/librespot" } ================================================ FILE: Cross.toml ================================================ [build] pre-build = [ "dpkg --add-architecture $CROSS_DEB_ARCH", "apt-get update", # bindgen requirements "apt-get install -y libclang-dev cmake", # alsa_backend,rodio_backend and base requirements "apt-get install -y libasound2-dev:$CROSS_DEB_ARCH libssl-dev:$CROSS_DEB_ARCH", # dbus_mpris "apt-get install -y libdbus-1-dev:$CROSS_DEB_ARCH", # pulseaudio_backend "apt-get install -y libpulse-dev:$CROSS_DEB_ARCH", # portaudio_backend "apt-get install -y portaudio19-dev:$CROSS_DEB_ARCH", ] [target.armv7-unknown-linux-gnueabihf] image = ":edge" # needed, since dbus and pulse dependencies on older ubuntu versions are messy ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: README.md ================================================ # Spotifyd [![Matrix][matrix-badge]](https://matrix.to/#/#spotifyd:matrix.org) [![GitHub Workflow Status][cd-badge]][github-actions] [![Github Actions - CI][ci-badge]][github-actions] > An open source Spotify client running as a UNIX daemon. [Project Website](https://spotifyd.rs) Spotifyd streams music just like the official client, but is more lightweight and supports more platforms. Spotifyd also supports the Spotify Connect protocol, which makes it show up as a device that can be controlled from the official clients. > __Note:__ Spotifyd requires a Spotify Premium account. __To read about how to install and configure Spotifyd, take a look at our [wiki][wiki]!__ ## Contributing We always appreciate help during the development of `spotifyd`! If you are new to programming, open source or Rust in general, take a look at issues tagged with [`good first issue`][good-first-issues]. These normally are easy to resolve and don't take much time to implement. ## Credits This project would not have been possible without the amazing reverse engineering work done in [librespot](https://github.com/librespot-org/librespot), mostly by [plietar](https://github.com/plietar). [github-actions]: https://github.com/Spotifyd/spotifyd/actions [good-first-issues]: https://github.com/Spotifyd/spotifyd/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [matrix-badge]: https://img.shields.io/matrix/spotifyd:matrix.org?logo=matrix&server_fqdn=matrix.org [cd-badge]: https://img.shields.io/github/actions/workflow/status/Spotifyd/spotifyd/cd.yml?label=continuous%20deployment&logo=github [ci-badge]: https://img.shields.io/github/actions/workflow/status/Spotifyd/spotifyd/ci.yml?label=continuous%20integration&logo=github [wiki]: https://spotifyd.github.io/spotifyd/ ================================================ FILE: contrib/spotifyd.conf ================================================ [global] #---------# # GENERAL # #---------# # The name that gets displayed under the connect tab on # official clients. #device_name = "device_name_in_spotify_connect" # The displayed device type in Spotify clients. # Can be unknown, computer, tablet, smartphone, speaker, t_v, # a_v_r (Audio/Video Receiver), s_t_b (Set-Top Box), and audio_dongle. #device_type = "speaker" # The directory used to store credentials and audio cache. # Default: infers a sensible cache directory (e.g. on Linux: $XDG_CACHE_HOME) # # Note: The file path does not get expanded. Environment variables and # shell placeholders like $HOME or ~ don't work! #cache_path = "/full/path/to/cache/directory" # If set to true, audio data does NOT get cached. # In this case, the cache is only used for credentials. #no_audio_cache = true # The maximal size of the cache directory in bytes # The example value corresponds to ~ 1GB #max_cache_size = 1000000000 # If set to true, `spotifyd` tries to bind to dbus (default is the session bus) # and expose MPRIS controls. When running headless, without the session bus, # you should set this to false, to avoid errors. If you still want to use MPRIS, # have a look at the `dbus_type` option. #use_mpris = true # The bus to bind to with the MPRIS interface. # Possible values: "session", "system" # The system bus can be used if no graphical session is available # (e.g. on headless systems) but you still want to be able to use MPRIS. # NOTE: You might need to add appropriate policies to allow spotifyd to # own the name. #dbus_type = "session" #-----------# # DISCOVERY # #-----------# # If set to true, this disables zeroconf discovery. # This can be useful, if one prefers to run a single-user instance. #disable_discovery = false # The port at which `spotifyd` is going to offer its service over the network (TCP). # If not set, a random port > 1024 is used. For the service to be discoverable on the # local network via mDNS, both the mDNS port (5353 UDP) and the random or fixed # zeroconf port need to be allowed through any active firewall. #zeroconf_port = 1234 #-------# # AUDIO # #-------# # The audio backend used to play music. To get # a list of possible backends, run `spotifyd --help`. #backend = "alsa" # use portaudio for macOS [homebrew] # The alsa audio device to stream audio. To get a # list of valid devices, run `aplay -L`, #device = "default" # omit for macOS # The PCM sample format to use. Possible values # are F32, S32, S24, S24_3, S16. # Change this value if you encounter errors like # "Alsa error PCM open ALSA function 'snd_pcm_hw_params_set_format' failed with error 'EINVAL: Invalid argument'" #audio_format = "S16" # The volume controller. Each one behaves different to # volume increases. For possible values, run # `spotifyd --help`. #volume_controller = "softvol" # use softvol for macOS # ! Only relevant for ALSA ! # The alsa control device. By default this is the same # name as the `device` field. #control = "default" # ! Only relevant for ALSA ! # The alsa mixer used by `spotifyd`. #mixer = "PCM" # omit for macOS # The audio bitrate. 96, 160 or 320 kbit/s #bitrate = 160 # Volume on startup between 0 and 100 #initial_volume = 90 # If set to true, enables volume normalisation between songs. #volume_normalisation = true # The normalisation pregain that is applied for each song. #normalisation_pregain = -10 #-------ä # OTHER # #-------# # After the music playback has ended, start playing similar songs based on the previous tracks. # By default, `spotifyd` infers this setting from the user settings. #autoplay = true # A command that gets executed in your shell after each song changes. #on_song_change_hook = "echo \"hook executed on $PLAYER_EVENT\"" # The proxy `spotifyd` will use to connect to spotify. #proxy = "http://proxy.example.org:8080" ================================================ FILE: contrib/spotifyd.service ================================================ [Unit] Description=A spotify playing daemon Documentation=https://github.com/Spotifyd/spotifyd Wants=sound.target After=sound.target Wants=network-online.target After=network-online.target [Service] ExecStart=/usr/bin/spotifyd --no-daemon Restart=always RestartSec=12 [Install] WantedBy=default.target ================================================ FILE: docs/.gitignore ================================================ book ================================================ FILE: docs/book.toml ================================================ [book] authors = ["@Spotifyd/maintainers and contributors"] language = "en" multilingual = false src = "src" title = "Spotifyd" ================================================ FILE: docs/src/Introduction.md ================================================ # Introduction This is the documentation of [spotifyd][spotifyd], which covers the installation and setup process as well as some advanced topics. ## Getting Help If you're stuck in the setup process or have a question, please join the [community matrix server][matrix]. We're always willing to help! [spotifyd]: https://github.com/Spotifyd/spotifyd [matrix]: https://matrix.to/#/#spotifyd:matrix.org ================================================ FILE: docs/src/SUMMARY.md ================================================ # Spotifyd [Introduction](./Introduction.md) - [Installation](./installation/README.md) - [Running as a service](./installation/service.md) - [Building from source](./installation/source.md) - [Cross-Compilation](./installation/cross-compilation.md) - [Configuration](./configuration/README.md) - [Authentication](./configuration/auth.md) - [Audio](./configuration/audio.md) - [Other settings](./configuration/other.md) - [Advanced Setup](./advanced/README.md) - [Running as systemd service](./advanced/systemd.md) - [Running as launchd service](./advanced/launchd.md) - [Using D-Bus to control `spotifyd`](./advanced/dbus.md) - [MPRIS on headless systems](./advanced/mpris.md) - [Extending spotifyd with hooks](./advanced/hooks.md) - [Troubleshooting](./troubleshooting.md) ================================================ FILE: docs/src/advanced/README.md ================================================ # Advanced Setup In this section, you will learn how to persist `spotifyd` as a system service, run hook scripts on certain events and control `spotifyd` via DBUS on headless systems. ================================================ FILE: docs/src/advanced/dbus.md ================================================ # Using D-Bus to control spotifyd If MPRIS support is built into your version and enabled (`--use-mpris` cli flag / `use_mpris = true` in config), `spotifyd` exposes some interfaces via D-Bus through which it provides information and can be controlled. Most of the time, you won't have to worry to much about the details, since tools like `playerctl` work out of the box with `spotifyd`. If you have some custom requirements or want to write custom scripts to control `spotifyd`, this section is for you. ## Available Interfaces Directly after startup, no interfaces will be available. Once we are connected to Spotify, `spotifyd` will request the name `rs.spotifyd.instance$PID` (where `PID=$(pidof spotifyd)`) and expose the interface `rs.spotifyd.Controls`. As soon as we are the playback device (e.g. because we are selected from another client or the `TransferPlayback` method has been called), `spotifyd` will additionally expose the MPRIS interfaces and request the name `org.mpris.MediaPlayer2.spotifyd.instance$PID`. ### Spotifyd Controls The `rs.spotifyd.Controls` interface exposes a few useful controls that are available even if we're not the active playback device. - Method `TransferPlayback`: transfers Spotify playback to `spotifyd` - Method `VolumeUp`: increases player volume - Method `VolumeDown`: decreases player volume Examples: ```bash dest=rs.spotifyd.instance$(pidof spotifyd) # increase volume dbus-send --print-reply --dest=$dest /rs/spotifyd/Controls rs.spotifyd.Controls.VolumeUp # become the active playback device dbus-send --print-reply --dest=$dest /rs/spotifyd/Controls rs.spotifyd.Controls.TransferPlayback ``` ### MPRIS The `org.mpris.MediaPlayer2` and `org.mpris.MediaPlayer2.Player` interfaces from the [MPRIS specification](https://specifications.freedesktop.org/mpris-spec/latest/) are implemented. Example usage: ```bash dest=org.mpris.MediaPlayer2.spotifyd.instance$(pidof spotifyd) # Start playback of some Spotify URI dbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.OpenUri string:spotify:track:4PTG3Z6ehGkBFwjybzWkR8 # Get metadata of the currently playing track dbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:org.mpris.MediaPlayer2.Player string:Metadata ``` ## Examples Starting Playback without Client: ```bash #!/bin/bash # optionally, we can start `spotifyd` here if ! pidof -q spotifyd then spotifyd --use-mpris fi dest=rs.spotifyd.instance$(pidof spotifyd) wait_for_name() { dst=$1 counter=0 # check if controls are available until [ $counter -gt 10 ] || (dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ListNames | grep -q "$dest") do sleep 0.3 ((counter++)) done if [ $counter -gt 10 ] then echo "waiting for spotifyd timed out" >&1 exit 1 fi } controls_name=rs.spotifyd.instance$(pidof spotifyd) wait_for_name $controls_name echo "Transferring Playback" dbus-send --print-reply --dest=$controls_name /rs/spotifyd/Controls rs.spotifyd.Controls.TransferPlayback # if URI is specified, start the playback there if [ -n "$1" ] then uri="$1" mpris_name=org.mpris.MediaPlayer2.spotifyd.instance$(pidof spotifyd) wait_for_name $mpris_name echo "Starting Playback of $uri" dbus-send --print-reply --dest=$mpris_name /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.OpenUri "string:$uri" else echo "Hint: specify an argument to start playback of a specific Spotify URI" fi ``` Sleep Timer: ```bash #!/bin/bash usage() { echo "Usage: $0 " >&1 exit 1 } [ -n "$1" ] || usage echo "Sleeping for $1 seconds" sleep $1 dest=org.mpris.MediaPlayer2.spotifyd.instance$(pidof spotifyd) dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ListNames | grep -q "$dest" if [ "$?" = "0" ] then dbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Stop # alternatively just pause: # dbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Pause else echo "No active spotifyd playback." fi ``` ================================================ FILE: docs/src/advanced/hooks.md ================================================ # User supplied Scripts If you want to create custom behaviour around `spotifyd`, one option is to look into the [D-Bus functionality](./dbus.md). But on headless systems or smaller projects, we also offer a hook API. On certain events, a hook can be executed with event details given as environment variables. To point `spotifyd` to such a script, use the `--onevent /path/to/script` cli arg / `on_song_change_hook = "/path/to/script"` configuration value. In order to learn about the available events and the available details, you can either create simple scripts which log the given environment variables or look at the output of `spotifyd`, which logs whenever the script is executed. The following scripts are intended to serve as inspiration for your own scripts. If you have written own scripts which you think might be useful to others, please create a PR adding them here! ## Dunst Notifications (Using Spotify API) This script will show a dunst notification when you play/change/stop Spotify (and when the music change). It is using spotify APIs to get music details. ### Dependencies * curl (Request to APIs) * xargs (Argument passing) * cut * jq (https://stedolan.github.io/jq) (for JSON parsing) ### How to use * Create a file containing the script below: ```bash user_id=YOUR_USER_ID # generated on https://developer.spotify.com/dashboard/applications secret_id=YOUR_SECRET_ID myToken=$(curl -s -X 'POST' -u $user_id:$secret_id -d grant_type=client_credentials https://accounts.spotify.com/api/token | jq '.access_token' | cut -d\" -f2) RESULT=$? if [ "$PLAYER_EVENT" = "start" ]; then if [ $RESULT -eq 0 ]; then curl -s -X 'GET' https://api.spotify.com/v1/tracks/$TRACK_ID -H 'Accept: application/json' -H 'Content-Type: application/json' -H "Authorization:\"Bearer $myToken\"" | jq '.name, .artists[].name, .album.name, .album.release_date, .track_number, .album.total_tracks' | xargs printf "\"Playing '%s' from '%s' (album: '%s' in %s (%s/%s))\"" | xargs notify-send --urgency=low --expire-time=3000 --icon=/usr/share/icons/gnome/32x32/actions/player_play.png --app-name=spotifyd spotifyd else echo "Cannot get token." fi elif [ "$PLAYER_EVENT" = "change" ]; then if [ $RESULT -eq 0 ]; then curl -s -X 'GET' https://api.spotify.com/v1/tracks/$TRACK_ID -H 'Accept: application/json' -H 'Content-Type: application/json' -H "Authorization:\"Bearer $myToken\"" | jq '.name, .artists[].name, .album.name, .album.release_date, .track_number, .album.total_tracks' | xargs printf "\"Music changed to '%s' from '%s' (album: '%s' in %s (%s/%s))\"" | xargs notify-send --urgency=low --expire-time=3000 --icon=/usr/share/icons/gnome/32x32/actions/player_fwd.png --app-name=spotifyd spotifyd else echo "Cannot get token." fi elif [ "$PLAYER_EVENT" = "stop" ]; then if [ $RESULT -eq 0 ]; then curl -s -X 'GET' https://api.spotify.com/v1/tracks/$TRACK_ID -H 'Accept: application/json' -H 'Content-Type: application/json' -H "Authorization:\"Bearer $myToken\"" | jq '.name, .artists[].name, .album.name, .album.release_date, .track_number, .album.total_tracks' | xargs printf "Stoping music (Last song: '%s' from '%s' (album: '%s' in %s (%s/%s)))\"" | xargs notify-send --urgency=low --expire-time=3000 --icon=/usr/share/icons/gnome/32x32/actions/player_stop.png --app-name=spotifyd spotifyd else echo "Cannot get token." fi else echo "Unknown event." fi ``` * Make this script executable (`chmod +x notification_script.sh`) * Add the line `onevent = "bash /home/YOU_USER/bin/spotifyNotifications.sh"` to your `spotifyd.conf` ================================================ FILE: docs/src/advanced/launchd.md ================================================ # Running as launchd service On macOS, the system wide and per-user daemon/agent manager is known as `launchd`. Interfacing with `launchd` is performed through `launchctl`. In order to use `spotifyd` as a service on macOS one must specify a `.plist` that represents the service, and place it in `/Library/LaunchDaemons`. Here is a .plist which works with macOS Catalina 10.15.3: ```xml Label rustlang.spotifyd ProgramArguments /usr/local/bin/spotifyd --config-path=/users/YourUserName/.config/spotifyd/spotifyd.conf --no-daemon UserName YourUserName KeepAlive ThrottleInterval 30 ``` Once present in the `/Library/LaunchDaemons` directory, the .plist must be loaded and started with the following commands. `sudo launchctl load -w /Library/LaunchDaemons/rustlang.spotifyd.plist` `sudo launchctl start /Library/LaunchDaemons/rustlang.spotifyd.plist` One may also unload/stop the service in a similar fashion replacing load/start with unload/stop. Note: * You should update "YourUserName" with your actual username for macOS (or remove "UserName" to run as root. * The string, `--no-daemon` is needed as launchd won't receive a PID for the process and will lose its remit over spotifyd. So it's best to include it, there will be no difference in use, nor will you see any log output. * macOS tries to start the daemon immediately on boot, and spotifyd fails if Wifi isn't connected. So one must have a keep alive (which retries if it fails to launch on boot), that retries after 30 seconds, which is enough for wifi etc to come up. ================================================ FILE: docs/src/advanced/mpris.md ================================================ # MPRIS on headless systems D-Bus offers two types of communication buses, the system and the session bus. By default and in most setups, MPRIS is expected to run on the session bus (for example, `playerctl` requires that). However, in headless contexts, the session bus is usually not available. In this case, you basically have two options: ## Option 1: Launch with `dbus-launch` By creating a wrapper script and using `dbus-launch`, `spotifyd` can be run with its own bus. This could look like the following `./spotify_wrapper.sh`: ```bash #!/bin/bash echo "$DBUS_SESSION_BUS_ADDRESS" > /tmp/spotifyd_bus echo "To use spotifyd's session bus, run 'export DBUS_SESSION_BUS_ADDRESS=$(cat /tmp/spotifyd_bus)'" spotifyd --no-daemon --use-mpris ``` Then, execute this script using `dbus-launch ./spotify_wrapper.sh` and follow the instructions in the output. ## Option 2: Using the system bus Instead of creating a new session bus, we can instead make use of the always existing system bus. To instruct `spotifyd` to use the system instead of the session bus, set the `--dbus-type system` cli flag / `dbus_type = "system"` config value. By default, requesting names on the system bus requires special priveleges, which `spotifyd` doesn't have. So, unless being run as root, this will fail. To allow a non-root user to request the `spotifyd` name, we need to create the following file (replacing `your user` by something sensible): `/usr/share/dbus-1/system.d/spotifyd.conf`: ```xml ``` Make sure to reload the D-Bus configuration with `systemctl reload dbus`. ================================================ FILE: docs/src/advanced/systemd.md ================================================ # Running as systemd service ## As as a user service A `systemd.service` unit file is provided in the project sources to help run spotifyd as a service on systemd-based systems. The file `contrib/spotifyd.service` should be copied to either: ```bash /etc/systemd/user/ ~/.config/systemd/user/ ``` Packagers of systemd-based distributions are encouraged to include the file in the former location. End-user should prefer the latter. It should be noted that some targets are not available when running under the user directory, such as `network-online.target`. Control of the daemon is handed over to systemd. The following command will start the service whenever the user logs in to the system. Logging out will stop the service. ```bash systemctl --user enable spotifyd.service --now ``` ## As a system wide service
When running spotifyd as a system wide service, it is not possible to access a user's keyring to obtain login credentials. Do not set `use_keyring = true` and do not specify `--use-keyring`, when running as a system wide service. To be able to access login credentials stored in the user's keyring, run spotifyd as a user service, as decribed above. Additionally, `use_mpris = true` or `--use-mpris` should not be used, since their intended usage is within user sessions (and not system-wide daemons). If you have very specific requirements and still want to control a system-wide `spotifyd` instance, head over to [MPRIS on headless systems](./mpris.md).
A `systemd.service` unit file is provided to help run spotifyd as a service on systemd-based systems. The file `contrib/spotifyd.service` should be copied to: ```bash /etc/systemd/system/ ``` Control of the daemon is handed over to systemd. The following example commands will start the service and keep it running across reboots. ```bash systemctl daemon-reload systemctl enable spotifyd.service --now ``` ================================================ FILE: docs/src/configuration/README.md ================================================ # Configuration `Spotifyd` is able to run without configuration at all and will assume default values for most of the fields. However, running without configuration will only allow you to connect to it via Spotify Connect if you're on the same network as the daemon. All configuration options can be specified directly as command line arguments or alternatively (in particular for permanent changes) be written into a configuration file. Throughout this section, we will always give both possibilities, e.g. `--cli-arg` for the cli variant / `config_value` for the config file variable. ## Config File `spotifyd` will look for its configuration at `/etc/spotifyd.conf`, `$XDG_CONFIG_PATH/spotifyd/spotifyd.conf` or if that is not set `~/.config/spotifyd/spotifyd.conf`. For other needs, you can point `spotifyd` to it's config file with the command line argument `--config-path `. You can start with the following documented config as an example and read through the subpages of this section: ```toml {{#include ../../../contrib/spotifyd.conf}} ``` ================================================ FILE: docs/src/configuration/audio.md ================================================ # Audio Configuration On most setups, audio should be Just Working™. If you have specific needs or something's not working, you might need to touch some of the config values. ## Backend > `-b/--backend` or `backend` in the config file. There are different audio backends available to choose from. See `spotifyd --help` to get the available names. ## Device selection > `--device` or `device` in the config file. Instead of using the default device, which can sometimes be different to what you'd prefer, you can ask `spotifyd` to use a specific audio device. The interpretation and available values depends on the backend you're using. - For ALSA, you can use `aplay -L` to get a list of possible devices. - For PulseAudio, run `pactl list short sinks` to get a list of possible names. ## Bitrate > `-B/--bitrate` or `bitrate` in the config file. To reduce bandwidth usage or increase quality, you can play with the bitrate. ## Volume Controller > `--volume-controller` or `volume_controller` in the config file. In most cases, leaving this at the default (`softvol`) should be fine. If you want your `spotifyd` volume to be synchronized with an output device's hardware volume, you can set this to `alsa` or `alsa_linear`. In both cases, you might also want to set the `mixer` device to set which device's volume should be changed. If you want to prevent the user to be able to adjust the volume, set this instead to `none`. ## Other For more interesting but less relevant audio options, have a look at `spotifyd --help` or [the example config](./). ================================================ FILE: docs/src/configuration/auth.md ================================================ # Authentication There are two different ways of authentication supported. ## Discovery on LAN By default, `spotifyd` advertises itself on the local network as a Spotify Connect device and will thus appear in **official** clients. After selecting it over there, you should be able to hear the sound coming out of your `spotifyd` device. For this to work, you need to make sure that your firewall isn't blocking the discovery. In particular, `spotifyd` uses two ports: - `5353 UDP`: MDNS service advertisement - A zeroconf port which uses TCP. By default, it is randomly chosen, but if you want to, you can configure it with the `--zeroconf-port` cli option / `zeroconf_port` config value. If you don't want discovery, because you're using one of the methods below, you can disable it via the `--disable-discovery` cli option / `disable_discovery = true` config value. > __Note:__ By default, the last active session will be remembered and reconnected once the service is restarted. ## Manual Login (via OAuth) If for some reason, discovery is not a viable option for your use case or you prefer a single-user instance, you can manually log in to your account and `spotifyd` will connect to this account by default. > __Note:__ Since the login method requires a web browser, trying this on headless systems is not recommended. As a workaround, you can log in on a machine with a working web browser and then copy the credential file onto the headless system. The location of the credential file will be `/oauth/credentials.json`. Before you begin the login flow, make sure that you won't need to change `cache_path` later on, because that location will be used to store the login data. Now, you're ready to run `spotifyd authenticate` (for available options, see `spotifyd auth --help`). This will ask you to browse to a link with your preferred web browser. On the page, you need to log into your Spotify account and confirm the connection. If the process was successful, you should see the message "Go back to your terminal :)" in your browser window. You can now close the tab and return to the terminal. Now, when running `spotifyd --no-daemon`, you should see that `spotifyd` automatically connects to your account. ``` Loading config from "..." [...] Login via OAuth as user . [...] Authenticated as '' ! ``` > __Note:__ Even if you logged into `spotifyd` using this method, discovery will still be enabled by default and any incoming connection will interrupt the current session. If you don't want or need this, you can disable it via the `--disable-discovery` cli option / `disable_discovery = true` config value. ================================================ FILE: docs/src/configuration/other.md ================================================ # Other settings ## Appearance You can customize, how your device is displayed in clients with `--device-name` / `device_name` and `--device-type` / `device_type` options. ## Caching You can enable audio data caching by setting a `--cache-path` / `cache_path` and limit its size with `--max-cache-size` / `max_cache_size`. ## MPRIS On linux desktop systems, you can enable `--use-mpris` / `use_mpris` (if your version has enabled that feature). This will give your desktop environment or tools like `playerctl` the option to display information about and control `spotifyd`. ================================================ FILE: docs/src/installation/README.md ================================================ # Installation Getting `spotifyd` on your system should be as easy as downloading a binary in most cases. If you'd like to learn how to compile `spotifyd` yourself, head over to [building from source](./source.md). ## Linux Some linux distributions include `spotifyd` in their official repositories. Have a look at [Repology](https://repology.org/project/spotifyd/versions) for a list of the distributions that currently ship an up-to-date version of `spotifyd`. If your distribution is not supported or the provided version is too old, skip to [this section](#installing-from-releases) in order to install one of our pre-built binaries. ## macOS If you're a homebrew user, installing `spotifyd` is as easy as running ```console brew install spotifyd ``` ## FreeBSD On FreeBSD, a package is available and can be installed with `pkg install spotifyd`. ## OpenBSD On OpenBSD, a package is available and can be installed with `pkg_add spotifyd`. ## Installing from releases If none of the above methods work for you, you can also use our provided binaries. First, you need to find a suitable binary for your platform. The provided binaries differ in the available features and the platform architecture that they were built for. You can find the latest binaries [here](https://github.com/Spotifyd/spotifyd/releases). **Feature Sets:** - `full`: **all audio backends** and **MPRIS** support - `default`: **some audio backends** (depending on your platform: PulseAudio, PortAudio, ALSA) and **MPRIS** support - `slim`: **one audio backend** (depending on your platform) and **no MPRIS** support (good for headless systems) If you're unsure which version to choose, just go for `default` on desktop systems and `slim` on headless systems. **Architecture:** If you're on Linux, check your platform architecture with `uname -m`: - `x86_64`: Download one of the `spotifyd-linux-x86_64-{full,default,slim}.tar.gz` packages. - `armhf`, `armv7`: Download one of the `spotifyd-linux-armv7-{full,default,slim}.tar.gz` packages. - `aarch64`: Download one of the `spotifyd-linux-aarch64-{full,default,slim}.tar.gz` - `armv6`: Unfortunately, we no longer support this architecture. If you still need this to work, please open an issue or join the [community matrix channel](https://matrix.to/#/#spotifyd:matrix.org) and we'll try to find a solution. If you're on macOS, download one of the `spotifyd-macos-{full,default,slim}.tar.gz` packages. You should now extract the downloaded archive, make the `spotifyd` file executable and copy it to a sensible location. This can be done using the following commands: ```console $ tar xzf spotifyd-*.tar.gz # extract $ cd spotifyd-*/ $ chmod +x spotifyd # make binary executable $ # move to correct location, e.g. on Linux: $ # for a user-wide installation (make sure that your $PATH includes ~/.local/bin) $ mv spotifyd ~/.local/bin/spotifyd $ # for a system-wide installation $ sudo chown root:root spotifyd $ sudo mv spotifyd /usr/local/bin/spotifyd ``` ## Running Now that you have installed `spotifyd`, you can check if everything was successful by running `spotifyd --version`. You should be ready to go now and after running `spotifyd --no-daemon`, it should appear in an **official** Spotify client which is on the same network. If this does not work, you can head over to the [troubleshooting section](../troubleshooting.md) or look at [different methods of authentication](../configuration/auth.md). ================================================ FILE: docs/src/installation/cross-compilation.md ================================================ # Cross-Compilation If you want to run `spotifyd` on lower-power hardware such as a RaspberryPi, but none of our prebuilt binaries suit your needs, you might want to cross-compile `spotifyd` on a more powerful machine and deploy the binary on the target system. ## Using `cross` The easiest way to cross-compile is using the amazing [`cross` project](https://github.com/cross-rs/cross). This way, the build environment comes already pre-configured. Follow the instructions in their README to install `cross`.
In the current latest release of cross (v0.2.5), some targets are too outdated and compilation will fail. Thus, it is currently recommended to install the latest version of `cross` from their git repo instead of a prebuilt binary.
Then, you should be able to run `cross build --target `, where target is one of the targets in `rustc --print target-list`. Please also refer to [the general from source guide](./source.md) for additional flags that you might want to append to that command. If this was successful, copy the resulting binary from `target//{release,debug}/spotifyd` to the `spotifyd` machine and try running it there. If `cross` doesn't support your target, you can try the alternative approach using Docker and QEMU below. If compilation of your target isn't working even though `cross` supports it, feel free to open an issue on our GitHub or join the [community matrix channel](https://matrix.to/#/#spotifyd:matrix.org) and ask there. ## Using Docker and QEMU We can also use `docker` to cross compile on every platform and OS that runs `docker` and `qemu`: 1. Setup a docker [custom builder](https://docs.docker.com/build/building/multi-platform/#create-a-custom-builder) ```shell docker buildx create \ --name container-builder \ --driver docker-container \ --use --bootstrap ``` If you are **not** using Docker-Desktop you might have to install [QEMU](https://docs.docker.com/build/building/multi-platform/#install-qemu-manually) 2. Create a docker `docker-compose.yml` Here we are building a `arm64` binary, so we set `platform: linux/arm64` ```yaml services: build-container: image: rust:1-bookworm platform: linux/arm64 command: bash -c " apt-get update && apt-get install -y \ libasound2-dev \ libssl-dev \ jq \ pkg-config && wget -O - https://api.github.com/repos/Spotifyd/spotifyd/tarball/$(\ curl -SsL https://api.github.com/repos/Spotifyd/spotifyd/releases/latest \ | jq '.tag_name' -r) \ | tar xzv -C /spotifyd --strip-components=1 && cargo build --release && cp /spotifyd/target/release/spotifyd /build/" working_dir: /spotifyd volumes: - ./:/build ``` 3. Run `docker compose up` This will copy the build `spotifyd` binary in the current directory. ================================================ FILE: docs/src/installation/service.md ================================================ # Running as a service Most people want to have `spotifyd` always running in the background. The preferred method to do this depends on the OS you're using. ## Linux If you installed `spotifyd` directly from your distribution, chances are that the installation includes a service definition such that you can run ```console $ systemctl --user start spotifyd # start spotifyd using systemd $ systemctl --user enable --now spotifyd # start spotifyd and enable starting on login ``` If you installed `spotifyd` some other way, head over to [the advanced section](../advanced/systemd.md) for further instructions. ## macOS If you installed `spotifyd` using brew, the following commands should do the trick ```console $ brew services run spotifyd # start the service once $ brew services start spotifyd # start spotifyd and enable starting on boot ``` If you installed `spotifyd` without brew, [the advanced section](../advanced/launchd.md) has got you covered. ## FreeBSD When installed via the package manager, the following commands are available: ```console $ sudo service spotifyd onestart # start spotifyd once $ sudo sysrc spotifyd_enable=YES # enable starting spotifyd on boot ``` ================================================ FILE: docs/src/installation/source.md ================================================ # Building from source The guide below assumes that you're building `spotifyd` on the system that you want to run it on. If you'd instead prefer to cross-compile, head over to [this section](./cross-compilation.md). You can also compile `spotifyd` yourself, allowing you to tailor it perfectly to your needs or get the latest fixes. `spotifyd` is written in Rust. You can download the toolchain (compiler and package manager) over at [rustup.rs](https://rustup.rs). Follow their instructions to get started. > __Note:__ Please make sure that you compile the package using the most recent `stable` version of Rust available through `rustup`. Some distro versions are quite outdated and might result in compilation errors. ## Required packages `spotifyd` might require additional libraries during build and runtime, depending on your platform and the way to compile it (static or dynamic). The following table shows the libraries needed for each OS respectively. | Target Platform | Libraries | |-----------------|------------------------------------------------------| | Fedora | alsa-lib-devel make gcc | | openSUSE | alsa-devel make gcc | | Debian | libasound2-dev libssl-dev libpulse-dev libdbus-1-dev | | Arch | base-devel alsa-lib libogg libpulse dbus | | macOS | dbus pkg-config portaudio | If you're building on a non-standard target, for example the RaspberryPi, you might need an additional `libclang-dev` and `cmake` package for one of our dependencies. Details can be found on [this page](https://aws.github.io/aws-lc-rs/requirements/linux.html). ## Installing with cargo To build and install the latest version of `spotifyd`, you can use the package manager for rust. The base command is the following ```console cargo install spotifyd --locked ``` If you would rather install from the latest commit on GitHub, download or clone the project, enter the directory and run ```console cargo install --path . --locked ``` > __Note:__ Both methods will install the binary in `$XDG_DATA_HOME/cargo/bin` or `$HOME/.cargo/bin`. To execute it, you must make sure that this location is part of your shell's `$PATH` variable. Also, you might have to change the paths when following other parts of this documentation. ## Compiling with cargo To just build the binary without installing, run ```console cargo build --release --locked ``` This will build the binary and leave the result at `./target/release/spotifyd`. ## Building a Debian package You can use the `cargo-deb` crate in order to build a Debian package from source. Install it by: ```console cargo install cargo-deb ``` Then you can build and install the Debian package with: ```console cargo deb --install ``` Note, that when building a Debian package, the `--release` is passed to the build command already and you do not need to specify it yourself. See for the flags that are set by default in `Cargo.toml`. ## Building an RPM package You can use the `cargo-generate-rpm` crate in order to build an RPM package from source. Install it by: ```console cargo install cargo-generate-rpm ``` Then you can build and install the RPM package with: ```console cargo build --release strip -s target/release/spotifyd cargo generate-rpm sudo rpm -Uvh target/generate-rpm/spotifyd-[VERSION].[ARCH].rpm ``` ## Feature Flags `spotifyd` is split into a base package plus additional features that can be toggled on or off during compilation. Those can be split into two groups: The audio backend features that are responsible for playing back the music and additional functionality features, which enhance your experience using `spotifyd`. | Feature Flag | Description | |--------------|-------------------------------------------------------------------------------------| | `alsa_backend` | Provides support for the ALSA backend. Should work in most setups and is enabled by default. | | `pulseaudio_backend` | Support for PulseAudio. | | `rodio_backend` | Rust-native implementation of audio backends on all platforms. Does not need any external packages to be installed. | | `portaudio_backend` | Audio backend that can be used on non-Linux systems. | | `rodiojack_backend` | Support for the Jack backend. | | `dbus_mpris` | Provides multimedia key support (Linux and BSD only) | To customize your build, pass a subset of the features listed above to any of the `cargo` commands above via `--features ,,...`. Disable the default feature `alsa_backend` with `--no-default-features`. So an example command could look like the following: ``` cargo install spotifyd --locked --no-default-features --features rodio_backend,dbus_mpris ``` ================================================ FILE: docs/src/troubleshooting.md ================================================ # Troubleshooting ## no sound on FreeBSD If you have correctly configured `spotifyd` to use `portaudio` and everything seems to be working except that there's no sound, you might have to switch to a different audio device. If you have `portaudio` as your backend and set your device to `?`, spotifyd will output all of the available PortAudio devices it can find on your system. This could look like the following ```bash - /dev/dsp0 (default) - /dev/dsp1 - /dev/dsp2 - /dev/dsp ``` Assume that the 4th device (index 3, starting from 0, `/dev/dsp`) is the output device that is needed. That coincides with the `pcm3` (also index 3, starting from 0) device that FreeBSD lists in `dmesg` as well as the `hw.snd.default_unit=3` sysctl that is used to set the device as OSS's default. It seems like the index number correlates across each of those enumerations. After setting `device = "/dev/dsp"` in the config, the sound should start working. If not, you can try the other possible values that are available. ================================================ FILE: hooks/pre-commit ================================================ #!/bin/sh # Author: Sven Lechner (SirWindfield) # License: GPLv3 require_clean_work_tree() { # Update index git update-index -q --ignore-submodules --refresh err=0 # Disallow unstaged changes in the working tree if ! git diff-files --quiet --ignore-submodules --; then echo >&2 "Cannot commit: you have unstaged changes." git diff-files --name-status -r --ignore-submodules -- >&2 err=1 fi if [ $err = 1 ]; then echo >&2 "Please stage or stash them." exit 1 fi } echo "→ Checking for local changes..." require_clean_work_tree echo "→ Formatting Rust code..." cargo fmt if [ $? -ne 0 ]; then exit 1 fi for path in $(git diff --name-only --cached); do git update-index --add $path done echo "→ Building pre-commit build artifacts..." cargo check --quiet --no-default-features --features "rodio_backend" if [ $? -ne 0 ]; then exit 1 fi cargo build --quiet --no-default-features --features "rodio_backend" # Linting is only done with the rodio backend and the keyring feature as those should be # compilable for every supported platform without external library needs. echo "→ Linting Rust code..." cargo clippy --no-default-features --features "rodio_backend" -- -D warnings echo "→ Testing Rust code..." cargo test --no-default-features --features "rodio_backend" ================================================ FILE: setup-dev-workspace.sh ================================================ #!/bin/sh # Author: Sven Lechner (SirWindfield) # License: GPLv3 # Copies all hooks into the .git/hooks directory cp hooks/* .git/hooks ================================================ FILE: src/alsa_mixer.rs ================================================ use alsa::device_name::HintIter; use color_eyre::{ Section, eyre::{self, Context, eyre}, }; use librespot_playback::mixer::{Mixer, MixerConfig}; use log::error; use std::sync::{Arc, Mutex, MutexGuard}; pub fn get_available_controls() -> alsa::Result { alsa::device_name::HintIter::new_str(None, "ctl") } pub struct AlsaMixer { pub mixer: Arc>, pub config: MixerConfig, } impl AlsaMixer { fn get_selem<'a>( &'a self, lock: &'a MutexGuard<'a, alsa::Mixer>, ) -> eyre::Result> { let selem_id = alsa::mixer::SelemId::new(&self.config.control, self.config.index); let selem = lock.find_selem(&selem_id).ok_or_else(|| { eyre!( "No control with name '{}' in alsa device '{}'", self.config.control, self.config.device, ) .with_suggestion(|| { format!( "maybe try one of the following for 'control':{}", lock.iter() .filter_map(|elem| { let selem = alsa::mixer::Selem::new(elem)?; if selem.has_playback_volume() { selem .get_id() .get_name() .ok() .map(|name| format!("\n- {name}")) } else { None } }) .collect::() ) }) })?; Ok(selem) } fn set_volume_with_err(&self, volume: u16) -> eyre::Result<()> { let lock = self.mixer.lock().expect("lock shouldn't be poisoned"); let elem = self.get_selem(&lock)?; let (min, max) = elem.get_playback_volume_range(); let volume_steps = (max - min) as f64; let normalised_volume = if matches!( self.config.volume_ctrl, librespot_playback::config::VolumeCtrl::Linear ) { (((volume as f64) / (u16::MAX as f64)) * volume_steps) as i64 + min } else { ((volume as f64 + 1.0).log((u16::MAX as f64) + 1.0) * volume_steps).floor() as i64 + min }; elem.set_playback_volume_all(normalised_volume)?; Ok(()) } fn get_volume_with_err(&self) -> eyre::Result { let lock = self.mixer.lock().expect("lock shouldn't be poisoned"); let elem = self.get_selem(&lock)?; let (min, max) = elem.get_playback_volume_range(); let volume_steps = (max - min) as f64; let vol = elem.get_playback_volume(alsa::mixer::SelemChannelId::mono())?; let normalized_volume = if matches!( self.config.volume_ctrl, librespot_playback::config::VolumeCtrl::Linear ) { ((vol - min) as f64 * u16::MAX as f64 / volume_steps).floor() as u16 } else { ((u16::MAX as f64 + 1.0).powf(((vol - min) as f64) / volume_steps) - 1.0).floor() as u16 }; Ok(normalized_volume) } } impl Mixer for AlsaMixer { fn open(config: MixerConfig) -> Result { let mixer = alsa::Mixer::new(&config.device, false) .wrap_err("failed to open mixer") .map_err(librespot_core::Error::invalid_argument)?; Ok(AlsaMixer { mixer: Arc::new(Mutex::new(mixer)), config, }) } fn volume(&self) -> u16 { match self.get_volume_with_err() { Ok(vol) => vol, Err(err) => { error!("failed to get volume from alsa device: {err:?}"); 0 } } } fn set_volume(&self, volume: u16) { match self.set_volume_with_err(volume) { Ok(_) => (), Err(err) => error!("Couldn't set volume of alsa device: {err:?}"), } } } ================================================ FILE: src/config.rs ================================================ use crate::utils; use clap::{ Args, Parser, Subcommand, ValueEnum, builder::{IntoResettable, PossibleValuesParser, TypedValueParser, ValueParser}, }; use color_eyre::{ Report, eyre::{Context, bail}, }; use directories::ProjectDirs; use gethostname::gethostname; use librespot_core::{cache::Cache, config::DeviceType as LSDeviceType, config::SessionConfig}; use librespot_playback::{ audio_backend, config::{AudioFormat as LSAudioFormat, Bitrate as LSBitrate, PlayerConfig}, dither::{DithererBuilder, TriangularDitherer, mk_ditherer}, }; use log::{debug, error, info, warn}; use serde::{ Deserialize, Deserializer, de::{self, Error, Unexpected}, }; use sha1::{Digest, Sha1}; use std::{ borrow::Cow, convert::TryInto, fs, path::{Path, PathBuf}, str::FromStr, }; use url::Url; const CONFIG_FILE_NAME: &str = "spotifyd.conf"; #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, ValueEnum)] #[serde(rename_all = "snake_case")] pub enum VolumeController { #[cfg(feature = "alsa_backend")] Alsa, #[cfg(feature = "alsa_backend")] AlsaLinear, #[serde(rename = "softvol")] SoftVolume, None, } // Spotify's device type (copied from it's config.rs) #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, ValueEnum)] #[serde(rename_all = "snake_case")] pub enum DeviceType { Unknown, Computer, Tablet, Smartphone, Speaker, #[serde(rename = "t_v")] Tv, #[serde(rename = "a_v_r")] Avr, #[serde(rename = "s_t_b")] Stb, AudioDongle, GameConsole, CastAudio, CastVideo, Automobile, Smartwatch, Chromebook, UnknownSpotify, CarThing, Observer, } impl From for LSDeviceType { fn from(item: DeviceType) -> Self { match item { DeviceType::Unknown => LSDeviceType::Unknown, DeviceType::Computer => LSDeviceType::Computer, DeviceType::Tablet => LSDeviceType::Tablet, DeviceType::Smartphone => LSDeviceType::Smartphone, DeviceType::Speaker => LSDeviceType::Speaker, DeviceType::Tv => LSDeviceType::Tv, DeviceType::Avr => LSDeviceType::Avr, DeviceType::Stb => LSDeviceType::Stb, DeviceType::AudioDongle => LSDeviceType::AudioDongle, DeviceType::GameConsole => LSDeviceType::GameConsole, DeviceType::CastAudio => LSDeviceType::CastAudio, DeviceType::CastVideo => LSDeviceType::CastVideo, DeviceType::Automobile => LSDeviceType::Automobile, DeviceType::Smartwatch => LSDeviceType::Smartwatch, DeviceType::Chromebook => LSDeviceType::Chromebook, DeviceType::UnknownSpotify => LSDeviceType::UnknownSpotify, DeviceType::CarThing => LSDeviceType::CarThing, DeviceType::Observer => LSDeviceType::Observer, } } } fn bitrate_parser() -> impl IntoResettable { let possible_values: PossibleValuesParser = ["96", "160", "320"].into(); possible_values.map(|val| match val.as_str() { "96" => Bitrate::Bitrate96, "160" => Bitrate::Bitrate160, "320" => Bitrate::Bitrate320, _ => unreachable!(), }) } /// Spotify's audio bitrate #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] pub enum Bitrate { Bitrate96, Bitrate160, Bitrate320, } impl<'de> Deserialize<'de> for Bitrate { fn deserialize>(deserializer: D) -> Result { match u16::deserialize(deserializer) { Ok(96) => Ok(Self::Bitrate96), Ok(160) => Ok(Self::Bitrate160), Ok(320) => Ok(Self::Bitrate320), Ok(x) => Err(D::Error::invalid_value( Unexpected::Unsigned(x.into()), &"a bitrate: 96, 160, 320", )), Err(e) => Err(e), } } } impl From for LSBitrate { fn from(bitrate: Bitrate) -> Self { match bitrate { Bitrate::Bitrate96 => LSBitrate::Bitrate96, Bitrate::Bitrate160 => LSBitrate::Bitrate160, Bitrate::Bitrate320 => LSBitrate::Bitrate320, } } } #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, ValueEnum)] #[serde(rename_all = "snake_case")] pub enum DBusType { Session, System, } #[derive(Clone, Copy, Debug, Deserialize, PartialEq, ValueEnum)] pub enum AudioFormat { F32, S32, S24, S24_3, S16, } impl From for LSAudioFormat { fn from(audio_format: AudioFormat) -> Self { match audio_format { AudioFormat::F32 => LSAudioFormat::F32, AudioFormat::S32 => LSAudioFormat::S32, AudioFormat::S24 => LSAudioFormat::S24, AudioFormat::S24_3 => LSAudioFormat::S24_3, AudioFormat::S16 => LSAudioFormat::S16, } } } fn possible_backends() -> Vec<&'static str> { audio_backend::BACKENDS.iter().map(|b| b.0).collect() } fn deserialize_backend<'de, D>(de: D) -> Result, D::Error> where D: Deserializer<'de>, { let backend = String::deserialize(de)?; let possible_backends = possible_backends(); if possible_backends.contains(&backend.as_str()) { Ok(Some(backend)) } else { Err(de::Error::invalid_value( Unexpected::Str(&backend), &format!( "a valid backend (available: {})", possible_backends.join(", ") ) .as_str(), )) } } fn number_or_string<'de, D>(de: D) -> Result, D::Error> where D: Deserializer<'de>, { let val = toml::Value::deserialize(de)?; let unexpected = match val { toml::Value::Integer(num) => { let num: u8 = num.try_into().map_err(de::Error::custom)?; return Ok(Some(num)); } toml::Value::String(num) => { return u8::from_str(&num) .map(Some) .inspect(|_| warn!("`initial_volume` should be a number rather than a string, this will become a hard error in the future")) .map_err(de::Error::custom) } toml::Value::Float(f) => Unexpected::Float(f), toml::Value::Boolean(b) => Unexpected::Bool(b), toml::Value::Datetime(_) => Unexpected::Other("datetime"), toml::Value::Array(_) => Unexpected::Seq, toml::Value::Table(_) => Unexpected::Map, }; Err(de::Error::invalid_type(unexpected, &"number")) } #[derive(Debug, Default, Parser)] #[command(version, about, long_about = None, args_conflicts_with_subcommands = true)] pub struct CliConfig { /// The path to the config file to use #[arg(long, value_name = "PATH", global = true)] pub config_path: Option, /// Prints more verbose output #[arg(short, long, action = clap::ArgAction::Count, global = true)] pub verbose: u8, /// If set, starts spotifyd without detaching #[arg(long)] pub no_daemon: bool, /// Path to PID file. #[cfg(unix)] #[arg(long, value_name = "PATH")] pub pid: Option, #[command(subcommand)] pub mode: Option, #[command(flatten)] pub shared_config: SharedConfigValues, } #[derive(Debug, Subcommand)] pub enum ExecutionMode { #[command(visible_alias = "auth")] Authenticate { /// The port to use for the OAuth redirect #[arg(long, default_value_t = 8000)] oauth_port: u16, }, } // A struct that holds all allowed config fields. // The actual config file is made up of two sections, spotifyd and global. #[derive(Clone, Default, Debug, Deserialize, PartialEq, Args)] pub struct SharedConfigValues { /// A script that gets evaluated in the user's shell when the song changes #[arg(visible_alias = "onevent", long, value_name = "CMD")] #[serde(alias = "onevent")] on_song_change_hook: Option, /// The cache path used to store credentials and music file artifacts #[arg(long, short, value_name = "PATH", global = true)] cache_path: Option, /// The maximal cache size in bytes #[arg(long, value_name = "BYTES")] max_cache_size: Option, /// Disable the use of audio cache #[arg( long, default_missing_value("true"), require_equals = true, num_args(0..=1), value_name = "BOOL" )] no_audio_cache: Option, /// The audio backend to use #[arg(long, short, value_parser = possible_backends())] #[serde(deserialize_with = "deserialize_backend", default)] backend: Option, /// The volume controller to use #[arg(value_enum, long, visible_alias = "volume-control")] #[serde(alias = "volume-control")] volume_controller: Option, /// The audio device (or pipe file) #[arg(long)] device: Option, /// The device name displayed in Spotify #[arg(long, short)] device_name: Option, /// The bitrate of the streamed audio data #[arg(long, short = 'B', value_parser = bitrate_parser())] bitrate: Option, /// The audio format of the streamed audio data #[arg(value_enum, long)] audio_format: Option, /// Initial volume between 0 and 100 #[arg(long)] #[serde(deserialize_with = "number_or_string", default)] initial_volume: Option, /// Enable to normalize the volume during playback #[arg( long, default_missing_value("true"), require_equals = true, num_args(0..=1), value_name = "BOOL" )] volume_normalisation: Option, /// A custom pregain applied before sending the audio to the output device #[arg(long)] normalisation_pregain: Option, #[arg( long, default_missing_value("true"), require_equals = true, num_args(0..=1), value_name = "BOOL" )] disable_discovery: Option, /// The port used for the Spotify Connect discovery #[arg(long)] zeroconf_port: Option, /// The proxy used to connect to spotify's servers #[arg(long, value_name = "URL")] proxy: Option, /// The device type shown to clients #[arg(value_enum, long)] device_type: Option, /// Start playing similar songs after your music has ended #[arg( long, default_missing_value("true"), require_equals = true, num_args(0..=1), value_name = "BOOL" )] #[serde(default)] autoplay: Option, #[cfg(feature = "alsa_backend")] #[command(flatten)] #[serde(flatten)] alsa_config: AlsaConfig, #[cfg(feature = "dbus_mpris")] #[command(flatten)] #[serde(flatten)] mpris_config: MprisConfig, } #[cfg(feature = "dbus_mpris")] #[derive(Debug, Default, Clone, Deserialize, Args, PartialEq, Eq)] pub struct MprisConfig { /// Enables the MPRIS interface #[arg( long, default_missing_value("true"), require_equals = true, num_args(0..=1), value_name = "BOOL" )] #[serde(alias = "use-mpris")] pub(crate) use_mpris: Option, /// The Bus-type to use for the MPRIS interface #[arg(value_enum, long)] pub(crate) dbus_type: Option, } #[cfg(feature = "alsa_backend")] #[derive(Debug, Default, Clone, Deserialize, Args, PartialEq, Eq)] pub struct AlsaConfig { /// The control device #[arg(long)] pub(crate) control: Option, /// The mixer to use #[arg(long)] pub(crate) mixer: Option, } #[derive(Debug, Default, Deserialize)] pub struct FileConfig { global: Option, spotifyd: Option, } impl FileConfig { pub fn get_merged_sections(self) -> Option { match (self.global, self.spotifyd) { (Some(global), Some(mut spotifyd)) => { spotifyd.merge_with(global); Some(spotifyd) } (global, spotifyd) => global.or(spotifyd), } } } #[derive(Copy, Clone)] enum KnownConfigProblem { #[cfg_attr( all(feature = "alsa_backend", feature = "dbus_mpris"), expect(dead_code) )] MissingFeature(&'static str), UsernamePassword, } fn get_known_config_problem(path: &serde_ignored::Path<'_>) -> Option { const DISABLED_CONFIGS: &[(KnownConfigProblem, &[&str])] = &[ #[cfg(not(feature = "alsa_backend"))] ( KnownConfigProblem::MissingFeature("alsa_backend"), &["control", "mixer"], ), #[cfg(not(feature = "dbus_mpris"))] ( KnownConfigProblem::MissingFeature("dbus_mpris"), &["use_mpris", "dbus_type"], ), ( KnownConfigProblem::UsernamePassword, &[ "username", "password", "username_cmd", "password_cmd", "use_keyring", ], ), ]; if let serde_ignored::Path::Map { key, .. } = path { for (problem, params) in DISABLED_CONFIGS { if params.contains(&key.as_str()) { return Some(*problem); } } } None } impl CliConfig { pub fn load_config_file_values(&mut self) -> Result<(), Report> { let config_file_path = match self.config_path.clone().or_else(get_config_file) { Some(p) => p, None => { info!("No config file specified. Running with default values"); return Ok(()); } }; info!("Loading config from {:?}", &config_file_path); let content = match fs::read_to_string(config_file_path) { Ok(s) => s, Err(e) => { info!("Failed reading config file: {}", e); return Ok(()); } }; let toml_de = toml::Deserializer::parse(&content)?; let config_content: FileConfig = serde_ignored::deserialize(toml_de, |path| { if let Some(problem) = get_known_config_problem(&path) { match problem { KnownConfigProblem::MissingFeature(feature) => { warn!( "The config key '{path}' is ignored, because the feature '{feature}' is missing in this build" ); } KnownConfigProblem::UsernamePassword => { warn!( "The config key '{path}' is ignored, because authentication with username and password is no longer supported by Spotify. Please use `spotifyd authenticate` instead" ); } } } else { warn!("Unknown key '{path}' in config will be ignored"); } })?; // The call to get_merged_sections consumes the FileConfig! if let Some(merged_sections) = config_content.get_merged_sections() { self.shared_config.merge_with(merged_sections); } Ok(()) } } impl SharedConfigValues { pub fn get_cache(&self, for_oauth: bool) -> color_eyre::Result { let Some(cache_path) = self.cache_path.as_deref().map(Cow::Borrowed).or_else(|| { ProjectDirs::from("", "", "spotifyd") .map(|dirs| Cow::Owned(dirs.cache_dir().to_path_buf())) }) else { bail!("Failed to determine cache directory, please specify one manually"); }; if for_oauth { let mut creds_path = cache_path.into_owned(); creds_path.push("oauth"); Cache::new(Some(creds_path), None, None, None) } else { let audio_cache = !self.no_audio_cache.unwrap_or(false); let mut creds_path = cache_path.to_path_buf(); creds_path.push("zeroconf"); Cache::new( Some(creds_path.as_path()), Some(cache_path.as_ref()), audio_cache.then_some(cache_path.as_ref()), self.max_cache_size, ) } .wrap_err("Failed to initialize cache") } pub fn proxy_url(&self) -> Option { match &self.proxy { Some(s) => match Url::parse(s) { Ok(url) => { if url.scheme() != "http" { error!("Only HTTP proxies are supported!"); None } else { Some(url) } } Err(err) => { error!("Invalid proxy URL: {}", err); None } }, None => { debug!("No proxy specified"); None } } } pub fn merge_with(&mut self, mut other: SharedConfigValues) { macro_rules! merge { ($a:expr; and $b:expr => {$($x:ident),+}) => { $($a.$x = $a.$x.take().or_else(|| $b.$x.take());)+ } } // Handles Option merging. merge!(self; and other => { backend, volume_normalisation, normalisation_pregain, bitrate, initial_volume, device_name, device, volume_controller, cache_path, no_audio_cache, on_song_change_hook, disable_discovery, zeroconf_port, proxy, device_type, max_cache_size, audio_format, autoplay }); #[cfg(feature = "dbus_mpris")] merge!(self.mpris_config; and other.mpris_config => {use_mpris, dbus_type}); #[cfg(feature = "alsa_backend")] merge!(self.alsa_config; and other.alsa_config => {mixer, control}); } } pub(crate) fn get_config_file() -> Option { let etc_conf = format!("/etc/{CONFIG_FILE_NAME}"); let dirs = directories::ProjectDirs::from("", "", "spotifyd")?; let mut path = dirs.config_dir().to_path_buf(); path.push(CONFIG_FILE_NAME); if path.exists() { Some(path) } else if Path::new(&etc_conf).exists() { let path: PathBuf = etc_conf.into(); Some(path) } else { None } } fn device_id(name: &str) -> String { hex::encode(Sha1::digest(name.as_bytes())) } pub(crate) struct SpotifydConfig { pub(crate) cache: Option, pub(crate) oauth_cache: Option, pub(crate) backend: Option, pub(crate) audio_device: Option, pub(crate) audio_format: LSAudioFormat, pub(crate) volume_controller: VolumeController, pub(crate) initial_volume: u16, pub(crate) device_name: String, pub(crate) player_config: PlayerConfig, pub(crate) session_config: SessionConfig, pub(crate) onevent: Option, #[cfg(unix)] pub(crate) pid: Option, pub(crate) shell: String, pub(crate) discovery: bool, pub(crate) zeroconf_port: Option, pub(crate) device_type: LSDeviceType, #[cfg(feature = "dbus_mpris")] pub(crate) mpris: MprisConfig, #[cfg(feature = "alsa_backend")] pub(crate) alsa_config: AlsaConfig, } pub(crate) fn get_internal_config(config: CliConfig) -> SpotifydConfig { let (cache, oauth_cache) = match ( config.shared_config.get_cache(false), config.shared_config.get_cache(true), ) { (Ok(cache), Ok(oauth_cache)) => (Some(cache), Some(oauth_cache)), (a, b) => { // at least one of the results are err let err = a.or(b).map(|_| ()).unwrap_err(); warn!("{err}"); (None, None) } }; let proxy_url = config.shared_config.proxy_url(); let bitrate: LSBitrate = config .shared_config .bitrate .unwrap_or(Bitrate::Bitrate160) .into(); let audio_format: LSAudioFormat = config .shared_config .audio_format .unwrap_or(AudioFormat::S16) .into(); let volume_controller = config .shared_config .volume_controller .unwrap_or(VolumeController::SoftVolume); let default_initial_volume = 90; let initial_volume: u16 = config .shared_config .initial_volume .filter(|val| { if (0..=100).contains(val) { true } else { warn!("initial_volume must be in range 0..100"); false } }) .map(|volume| (volume as i32 * (u16::MAX as i32) / 100) as u16) .unwrap_or((default_initial_volume * (u16::MAX as i32) / 100) as u16); let device_name = config .shared_config .device_name .filter(|s| !s.trim().is_empty()) .unwrap_or_else(|| format!("{}@{}", "Spotifyd", gethostname().to_string_lossy())); let device_id = device_id(&device_name); let normalisation_pregain = config.shared_config.normalisation_pregain.unwrap_or(0.0); let device_type = config .shared_config .device_type .unwrap_or(DeviceType::Speaker) .into(); #[cfg(unix)] let pid = config.pid.map(|f| { f.into_os_string() .into_string() .expect("Failed to convert PID file path to valid Unicode") }); let shell = utils::get_shell().unwrap_or_else(|| { info!("Unable to identify shell. Defaulting to \"sh\"."); "sh".to_string() }); // choose default ditherer the same way librespot does let ditherer: Option = match audio_format { LSAudioFormat::S16 | LSAudioFormat::S24 | LSAudioFormat::S24_3 => { Some(mk_ditherer::) } _ => None, }; // TODO: when we were on librespot 0.1.5, all PlayerConfig values were available in the // Spotifyd config. The upgrade to librespot 0.2.0 introduces new config variables, and we // should consider adding them to Spotifyd's config system. let pc = PlayerConfig { bitrate, normalisation: config.shared_config.volume_normalisation.unwrap_or(false), normalisation_pregain_db: normalisation_pregain, gapless: true, ditherer, ..Default::default() }; SpotifydConfig { cache, oauth_cache, backend: config.shared_config.backend, audio_device: config.shared_config.device, audio_format, volume_controller, initial_volume, device_name, player_config: pc, session_config: SessionConfig { autoplay: config.shared_config.autoplay, device_id, proxy: proxy_url, ap_port: Some(443), ..Default::default() }, onevent: config.shared_config.on_song_change_hook, shell, discovery: !config.shared_config.disable_discovery.unwrap_or(false), zeroconf_port: config.shared_config.zeroconf_port, device_type, #[cfg(unix)] pid, #[cfg(feature = "dbus_mpris")] mpris: config.shared_config.mpris_config, #[cfg(feature = "alsa_backend")] alsa_config: config.shared_config.alsa_config, } } #[cfg(test)] mod tests { use super::*; #[test] fn test_section_merging() { let mut spotifyd_section = SharedConfigValues { device_type: Some(DeviceType::Computer), ..Default::default() }; let global_section = SharedConfigValues { device_name: Some("spotifyd-test".to_string()), ..Default::default() }; // The test only makes sense if both sections differ. assert_ne!(spotifyd_section, global_section); let file_config = FileConfig { global: Some(global_section), spotifyd: Some(spotifyd_section.clone()), }; let merged_config = file_config.get_merged_sections().unwrap(); // Add the new field to spotifyd section. spotifyd_section.device_name = Some("spotifyd-test".to_string()); assert_eq!(merged_config, spotifyd_section); } #[test] fn test_example_config() { let example_config = include_str!("../contrib/spotifyd.conf"); let config: FileConfig = toml::Deserializer::parse(example_config) .and_then(|toml_de| { serde_ignored::deserialize(toml_de, |path| { panic!("Unknown key in (commented) example config: '{}'", path) }) }) .expect("Commented example config should be valid"); assert_eq!( (config.global, config.spotifyd), (Some(SharedConfigValues::default()), None), "example config should not do anything by default, but contain the global section" ); let uncommented_example_config = example_config .lines() .map(|line| { // uncomment any line starting with #[a-zA-Z] line.strip_prefix("#") .filter(|rest| { // uncomment if the rest is a valid config line // if alsa_backend is not enabled, ignore the 'backend = "alsa"' line rest.starts_with(char::is_alphabetic) && (cfg!(feature = "alsa_backend") || !rest.starts_with("backend")) }) .unwrap_or(line) }) .collect::>() .join("\n"); let config: FileConfig = toml::Deserializer::parse(&uncommented_example_config) .and_then(|toml_de| { serde_ignored::deserialize(toml_de, |path| { if !matches!( get_known_config_problem(&path), Some(KnownConfigProblem::MissingFeature(_)) ) { panic!("Unknown configuration key in example config: {}", path); } }) }) .expect("Uncommented example config should be valid"); assert!( config.spotifyd.is_none(), "example config should not have a spotifyd section" ); assert!( config .global .is_some_and(|global| global != SharedConfigValues::default()), "uncommented example config should contain some values" ); } } ================================================ FILE: src/dbus_mpris.rs ================================================ use crate::config::DBusType; use chrono::{Duration, prelude::*}; use dbus::{ MethodErr, arg::{RefArg, Variant}, channel::{MatchingReceiver, Sender}, message::{MatchRule, SignalArgs}, nonblock::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged, }; use dbus_crossroads::{Crossroads, IfaceToken}; use dbus_tokio::connection::{self, IOResourceError}; use futures::{ Future, task::{Context, Poll}, }; use librespot_connect::{LoadContextOptions, LoadRequest, LoadRequestOptions, Spirc}; use librespot_core::{Session, SpotifyUri}; use librespot_metadata::audio::AudioItem; use librespot_playback::player::PlayerEvent; use log::{debug, warn}; use std::convert::TryFrom; use std::{ collections::HashMap, pin::Pin, sync::{Arc, RwLock}, }; use thiserror::Error; use time::format_description::well_known::Iso8601; use tokio::{ runtime::Handle, sync::{ Mutex, mpsc::{UnboundedReceiver, UnboundedSender}, }, }; type DbusMap = HashMap>>; const MPRIS_PATH: &str = "/org/mpris/MediaPlayer2"; const CONTROLS_PATH: &str = "/rs/spotifyd/Controls"; pub enum ControlMessage { SetSession(Arc, Session), DropSession, Shutdown, } pub(crate) struct DbusServer { dbus_future: Pin>>>, control_tx: UnboundedSender, } impl DbusServer { pub fn new(event_rx: UnboundedReceiver, dbus_type: DBusType) -> DbusServer { let (control_tx, control_rx) = tokio::sync::mpsc::unbounded_channel(); let dbus_future = Box::pin(create_dbus_server(event_rx, control_rx, dbus_type)); DbusServer { dbus_future, control_tx, } } pub fn set_session(&self, spirc: Arc, session: Session) -> Result<(), DbusError> { self.control_tx .send(ControlMessage::SetSession(spirc, session)) .map_err(|_| DbusError::ControlChannelBroken) } pub fn drop_session(&self) -> Result<(), DbusError> { self.control_tx .send(ControlMessage::DropSession) .map_err(|_| DbusError::ControlChannelBroken) } /// Sends a shutdown signal and returns false, if the server was already shut down. pub fn shutdown(&self) -> bool { self.control_tx.send(ControlMessage::Shutdown).is_ok() } } #[derive(Debug, Error)] pub(crate) enum DbusError { #[error("Failed to initialize D-Bus: {}", .0)] InitFailure(#[from] dbus::Error), #[error("The connection was terminated unexpectedly: {}", .0)] ConnectionFailure(#[from] IOResourceError), #[error("Unexpectedly lost control of dbus server")] ControlChannelBroken, } impl Future for DbusServer { type Output = Result<(), DbusError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { self.dbus_future.as_mut().poll(cx) } } #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum PlaybackStatus { Playing, Paused, Stopped, } impl PlaybackStatus { fn to_mpris(self) -> &'static str { match self { PlaybackStatus::Playing => "Playing", PlaybackStatus::Paused => "Paused", PlaybackStatus::Stopped => "Stopped", } } } #[derive(Debug)] struct Position { last_position: Duration, last_update: DateTime, } impl Position { fn new() -> Self { Self { last_position: Duration::zero(), last_update: Local::now(), } } fn update_position(&mut self, new_position: Duration) { self.last_update = Local::now(); self.last_position = new_position; } fn get_position(&self) -> Duration { (Local::now() - self.last_update) + self.last_position } } #[derive(Clone, Copy, Debug)] enum RepeatState { None, Track, All, } impl RepeatState { fn to_mpris(self) -> &'static str { match self { RepeatState::None => "None", RepeatState::Track => "Track", RepeatState::All => "Playlist", } } fn repeat_track(self) -> bool { matches!(self, RepeatState::Track) } fn repeat_context(self) -> bool { !matches!(self, RepeatState::None) } } impl From<(bool, bool)> for RepeatState { fn from((context, track): (bool, bool)) -> Self { if context { if track { RepeatState::Track } else { RepeatState::All } } else { RepeatState::None } } } #[derive(Debug)] struct CurrentStateInner { status: PlaybackStatus, position: Option, audio_item: Option>, volume: u16, shuffle: bool, repeat: RepeatState, play_request_id: Option, } fn insert_attr(map: &mut DbusMap, attr: impl ToString, value: impl RefArg + 'static) { map.insert(attr.to_string(), Variant(Box::new(value))); } impl CurrentStateInner { fn mpris_volume(&self) -> f64 { self.volume as f64 / u16::MAX as f64 } fn get_position(&self) -> Option { let position = self.position.as_ref()?; match self.status { PlaybackStatus::Playing => Some(position.get_position()), PlaybackStatus::Paused => Some(position.last_position), PlaybackStatus::Stopped => None, } } fn update_position(&mut self, position: Duration) { self.position .get_or_insert_with(Position::new) .update_position(position); } fn handle_event(&mut self, event: PlayerEvent) -> (DbusMap, bool) { let mut changed = DbusMap::new(); let mut seeked = false; // note that get_play_request_id is None on PlayRequestIdChanged if Option::zip(self.play_request_id, event.get_play_request_id()) .is_some_and(|(cur_id, event_id)| cur_id != event_id) { debug!("discarding event due to play_request_id mismatch"); return (changed, seeked); } debug!("handling event {event:?}"); match event { PlayerEvent::VolumeChanged { volume } => { self.volume = volume; insert_attr(&mut changed, "Volume", self.mpris_volume()); } PlayerEvent::Stopped { .. } => { self.status = PlaybackStatus::Stopped; self.audio_item = None; insert_attr( &mut changed, "PlaybackStatus", self.status.to_mpris().to_string(), ); insert_attr(&mut changed, "Metadata", self.to_metadata()); } PlayerEvent::Playing { position_ms, .. } => { if self.status != PlaybackStatus::Playing { self.status = PlaybackStatus::Playing; insert_attr( &mut changed, "PlaybackStatus", self.status.to_mpris().to_string(), ); } self.update_position(Duration::milliseconds(position_ms as i64)); seeked = true; } PlayerEvent::Paused { position_ms, .. } => { if self.status != PlaybackStatus::Paused { self.status = PlaybackStatus::Paused; insert_attr( &mut changed, "PlaybackStatus", self.status.to_mpris().to_string(), ) } self.update_position(Duration::milliseconds(position_ms as i64)); seeked = true; } PlayerEvent::TrackChanged { audio_item } => { self.audio_item = Some(audio_item); insert_attr(&mut changed, "Metadata", self.to_metadata()); } PlayerEvent::PositionCorrection { position_ms, .. } | PlayerEvent::PositionChanged { position_ms, .. } | PlayerEvent::Seeked { position_ms, .. } => { self.update_position(Duration::milliseconds(position_ms as i64)); seeked = true; } PlayerEvent::ShuffleChanged { shuffle } => { self.shuffle = shuffle; insert_attr(&mut changed, "Shuffle", self.shuffle); } PlayerEvent::RepeatChanged { context, track } => { self.repeat = (context, track).into(); insert_attr( &mut changed, "LoopStatus", self.repeat.to_mpris().to_string(), ) } PlayerEvent::PlayRequestIdChanged { play_request_id } => { self.play_request_id = Some(play_request_id); } PlayerEvent::Preloading { .. } | PlayerEvent::Loading { .. } | PlayerEvent::TimeToPreloadNextTrack { .. } | PlayerEvent::EndOfTrack { .. } | PlayerEvent::Unavailable { .. } | PlayerEvent::AutoPlayChanged { .. } | PlayerEvent::FilterExplicitContentChanged { .. } | PlayerEvent::SessionConnected { .. } | PlayerEvent::SessionDisconnected { .. } | PlayerEvent::SessionClientChanged { .. } => (), } (changed, seeked) } fn to_metadata(&self) -> DbusMap { let mut m = HashMap::new(); insert_attr( &mut m, "mpris:trackid", uri_to_object_path( self.audio_item .as_deref() .and_then(|item| item.track_id.to_uri().ok()) .as_deref(), ), ); if let Some(audio_item) = self.audio_item.as_deref() { if let Some(length) = Duration::milliseconds(audio_item.duration_ms as i64).num_microseconds() { insert_attr(&mut m, "mpris:length", length); } if let Some(cover) = audio_item.covers.iter().max_by_key(|im| im.width) { insert_attr(&mut m, "mpris:artUrl", cover.url.clone()); } insert_attr(&mut m, "xesam:title", audio_item.name.clone()); use librespot_metadata::audio::UniqueFields::*; match &audio_item.unique_fields { Local { artists, album, album_artists, number, disc_number, path, } => { if let Some(artists) = artists { insert_attr(&mut m, "xesam:artist", artists.clone()); } if let Some(album) = album { insert_attr(&mut m, "xesam:album", album.clone()); } if let Some(album_artists) = album_artists { insert_attr(&mut m, "xesam:albumArtist", album_artists.clone()); } if let Some(number) = number { insert_attr(&mut m, "xesam:trackNumber", *number); } if let Some(disc_number) = disc_number { insert_attr(&mut m, "xesam:discNumber", *disc_number); } insert_attr(&mut m, "xesam:url", format!("file://{:?}", path)); } Track { artists, album, album_artists, popularity, number, disc_number, } => { insert_attr( &mut m, "xesam:artist", artists .iter() .map(|artist| artist.name.clone()) .collect::>(), ); insert_attr(&mut m, "xesam:album", album.clone()); insert_attr(&mut m, "xesam:albumArtist", album_artists.clone()); insert_attr(&mut m, "xesam:autoRating", (*popularity as f64) / 100.0); insert_attr(&mut m, "xesam:trackNumber", *number); insert_attr(&mut m, "xesam:discNumber", *disc_number); } Episode { description, publish_time, show_name, } => { insert_attr(&mut m, "xesam:artist", vec![show_name.clone()]); insert_attr(&mut m, "xesam:comment", vec![description.clone()]); if let Ok(formatted_publish) = publish_time.format(&Iso8601::DEFAULT) { insert_attr(&mut m, "xesam:contentCreated", formatted_publish); } } } } m } } #[derive(Debug)] struct CurrentState(RwLock); #[derive(Clone, Copy, Debug, Error)] #[error("internal state no longer available due to application error")] struct StatePoisonError; impl From for MethodErr { fn from(value: StatePoisonError) -> Self { MethodErr::failed(&value) } } impl CurrentState { fn new(inner: CurrentStateInner) -> Self { Self(RwLock::new(inner)) } fn read(&self) -> Result, StatePoisonError> { self.0.read().map_err(|_| StatePoisonError) } fn write( &self, ) -> Result, StatePoisonError> { self.0.write().map_err(|_| StatePoisonError) } } async fn create_dbus_server( mut event_rx: UnboundedReceiver, mut control_rx: UnboundedReceiver, dbus_type: DBusType, ) -> Result<(), DbusError> { let (resource, conn) = match dbus_type { DBusType::Session => connection::new_session_sync(), DBusType::System => connection::new_system_sync(), }?; let mut connection_task = tokio::spawn(async { Err::<(), _>(resource.await) }); // this name will be used, once we can provide the mpris interface let mpris_name = format!( "org.mpris.MediaPlayer2.spotifyd.instance{}", std::process::id() ); // this name will always be available to allow easy discovery of the controls interface let spotifyd_name = format!("rs.spotifyd.instance{}", std::process::id()); conn.request_name(&spotifyd_name, false, true, true).await?; let mut cr = Crossroads::new(); cr.set_async_support(Some(( conn.clone(), Box::new(|x| { tokio::spawn(x); }), ))); let current_state = Arc::new(CurrentState::new(CurrentStateInner { status: PlaybackStatus::Stopped, position: None, audio_item: None, volume: u16::MAX, shuffle: false, repeat: RepeatState::None, play_request_id: None, })); let (quit_tx, mut quit_rx) = tokio::sync::mpsc::unbounded_channel(); let cr = Arc::new(Mutex::new(cr)); let crossroads = cr.clone(); conn.start_receive( MatchRule::new_method_call(), Box::new(move |msg, conn| { tokio::task::block_in_place(|| { let mut cr = cr.blocking_lock(); cr.handle_message(msg, conn).unwrap(); }); true }), ); let mut spirc: Option> = None; let mut session: Option = None; struct ConnectionData { conn_id: String, seeked_fn: SeekedSignal, } let mut cur_conn: Option = None; loop { tokio::select! { _ = quit_rx.recv() => { break; } result = &mut connection_task => { result.expect("the dbus connection panicked")?; break; } event = event_rx.recv() => { let event = event.expect("event channel was unexpectedly closed"); if let PlayerEvent::SessionConnected { connection_id, .. } = event { let mut cr = crossroads.lock().await; let seeked_fn = register_player_interface( &mut cr, spirc.clone().unwrap(), session.clone().unwrap(), current_state.clone(), quit_tx.clone(), ); if cur_conn.is_none() { conn.request_name(&mpris_name, true, true, true).await?; } cur_conn = Some(ConnectionData { conn_id: connection_id, seeked_fn }); } else if let PlayerEvent::SessionDisconnected { connection_id, .. } = event { // if this message isn't outdated yet, we vanish from the bus if cur_conn.as_ref().is_some_and(|d| d.conn_id == connection_id) { let mut cr = crossroads.lock().await; conn.release_name(&mpris_name).await?; cr.remove::<()>(&MPRIS_PATH.into()); cur_conn = None; } } else { let (changed, seeked) = current_state .write() .expect("state has been poisoned") .handle_event(event); if seeked { let position = current_state .read() .expect("state has been poisoned") .get_position(); if let Some((ConnectionData { seeked_fn, .. }, position)) = Option::zip(cur_conn.as_ref(), position) { let msg = seeked_fn( &MPRIS_PATH.into(), &(position.num_microseconds().unwrap_or_default(),), ); conn.send(msg).unwrap(); } } if !changed.is_empty() { let msg = PropertiesPropertiesChanged { interface_name: "org.mpris.MediaPlayer2.Player".to_owned(), changed_properties: changed, invalidated_properties: Vec::new(), }; conn.send( msg.to_emit_message(&dbus::Path::new(MPRIS_PATH).unwrap()), ) .unwrap(); } } } control = control_rx.recv() => { let control = control.expect("control channel was unexpectedly closed"); match control { ControlMessage::Shutdown => { break; }, ControlMessage::SetSession(new_spirc, new_session) => { let mut cr = crossroads.lock().await; register_controls_interface(&mut cr, new_spirc.clone()); spirc = Some(new_spirc); session = Some(new_session); } ControlMessage::DropSession => { let mut cr = crossroads.lock().await; conn.release_name(&mpris_name).await?; cr.remove::<()>(&MPRIS_PATH.into()); cr.remove::<()>(&CONTROLS_PATH.into()); spirc = None; session = None; cur_conn = None; } } } } } conn.release_name(&mpris_name).await?; conn.release_name(&spotifyd_name).await?; Ok(()) } type SeekedSignal = Box dbus::Message + Send + Sync + 'static>; fn register_player_interface( cr: &mut Crossroads, spirc: Arc, session: Session, current_state: Arc, quit_tx: tokio::sync::mpsc::UnboundedSender<()>, ) -> SeekedSignal { // The following methods and properties are part of the MediaPlayer2 interface. // https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html let media_player2_interface = cr.register("org.mpris.MediaPlayer2", move |b| { let mut quit_tx = Some(quit_tx); b.method("Raise", (), (), move |_, _, (): ()| { // noop Ok(()) }); b.method("Quit", (), (), move |_, _, (): ()| { quit_tx.take().unwrap().send(()).ok(); Ok(()) }); b.property("CanQuit") .emits_changed_const() .get(|_, _| Ok(true)); b.property("CanRaise") .emits_changed_const() .get(|_, _| Ok(false)); b.property("CanSetFullscreen") .emits_changed_const() .get(|_, _| Ok(false)); b.property("HasTrackList") .emits_changed_const() .get(|_, _| Ok(false)); b.property("Identity") .emits_changed_const() .get(|_, _| Ok("Spotifyd".to_string())); b.property("SupportedUriSchemes") .emits_changed_const() .get(|_, _| Ok(vec!["spotify".to_string()])); b.property("SupportedMimeTypes") .emits_changed_const() .get(|_, _| Ok(Vec::::new())); }); // The following methods and properties are part of the MediaPlayer2.Player interface. // https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html let mut seeked_signal = None; let player_interface: IfaceToken<()> = cr.register("org.mpris.MediaPlayer2.Player", |b| { seeked_signal = Some(b.signal::<(i64,), _>("Seeked", ("Position",)).msg_fn()); let local_spirc = spirc.clone(); b.method("VolumeUp", (), (), move |_, _, (): ()| { local_spirc.volume_up().map_err(|e| MethodErr::failed(&e)) }) .deprecated(); let local_spirc = spirc.clone(); b.method("VolumeDown", (), (), move |_, _, (): ()| { local_spirc.volume_down().map_err(|e| MethodErr::failed(&e)) }) .deprecated(); let local_spirc = spirc.clone(); b.method("Next", (), (), move |_, _, (): ()| { local_spirc.next().map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); b.method("Previous", (), (), move |_, _, (): ()| { local_spirc.prev().map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); b.method("Pause", (), (), move |_, _, (): ()| { local_spirc.pause().map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); b.method("PlayPause", (), (), move |_, _, (): ()| { warn!("PlayPause method called via mpris"); local_spirc.play_pause().map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); b.method("Play", (), (), move |_, _, (): ()| { warn!("Play method called via mpris"); local_spirc.play().map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); b.method("Stop", (), (), move |_, _, (): ()| { let pause_playback = false; local_spirc .disconnect(pause_playback) .map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); let local_state = current_state.clone(); b.method("Seek", ("offset",), (), move |_, _, (offset,): (i64,)| { let Some(position) = local_state.read()?.get_position() else { return Err(dbus::MethodErr::failed( "cannot seek while playback is stopped", )); }; let new_pos = position + Duration::microseconds(offset); let new_pos_ms = u32::try_from(new_pos.num_milliseconds()).map_err(|err| { dbus::MethodErr::invalid_arg(&format!("new position out of bounds: {err}")) })?; if let Err(err) = local_spirc.set_position_ms(new_pos_ms) { warn!("failed to seek by {offset}ms: {err}"); return Err(dbus::MethodErr::failed(&err)); } Ok(()) }); let local_spirc = spirc.clone(); let local_state = current_state.clone(); b.method( "SetPosition", ("track_id", "position"), (), move |_, _, (track_id, pos): (dbus::Path, i64)| { let Some((current_track_id, duration)) = local_state .read()? .audio_item .as_ref() .map(|item| (item.track_id.clone(), item.duration_ms)) else { return Err(dbus::MethodErr::failed( "can set position while nothing is playing", )); }; let duration = Duration::milliseconds(duration.into()); if !track_id.ends_with(¤t_track_id.to_id().unwrap()) { // as per mpris spec: ignore as stale return Ok(()); } let new_position = Duration::microseconds(pos); if new_position < Duration::zero() || new_position > duration { // ignore as per spec return Ok(()); } if let Err(err) = local_spirc.set_position_ms(new_position.num_milliseconds() as u32) { return Err(dbus::MethodErr::failed(&err)); } Ok(()) }, ); let local_spirc = spirc.clone(); let local_state = current_state.clone(); b.method("OpenUri", ("uri",), (), move |_, _, (uri,): (String,)| { let uri = SpotifyUri::from_uri(uri.as_str()).map_err(|e| MethodErr::invalid_arg(&e))?; let CurrentStateInner { shuffle, repeat, .. } = *local_state.read()?; let session = session.clone(); let (playing_track_index, context_uri) = Handle::current() .block_on(async move { use librespot_metadata::*; Ok::<_, librespot_core::Error>(match uri { SpotifyUri::Track { .. } => { let track = Track::get(&session, &uri).await?; if track.number == 0 { warn!("track.number is not expected to be 0- but 1-indexed"); } ((track.number - 1).max(0) as u32, track.album.id.to_uri()?) } SpotifyUri::Album { .. } | SpotifyUri::Artist { .. } | SpotifyUri::Playlist { .. } | SpotifyUri::Episode { .. } | SpotifyUri::Show { .. } => (0, uri.to_uri()?), SpotifyUri::Local { .. } | SpotifyUri::Unknown { .. } => { return Err(librespot_core::Error::unimplemented( "this type of uri is not supported", )); } }) }) .map_err(|e| MethodErr::failed(&e))?; warn!( "loading context_uri {context_uri} with playing_track_index {playing_track_index}" ); local_spirc .load(LoadRequest::from_context_uri( context_uri, LoadRequestOptions { start_playing: true, seek_to: 0, context_options: Some(LoadContextOptions::Options( librespot_connect::Options { shuffle, repeat: repeat.repeat_context(), repeat_track: repeat.repeat_track(), }, )), playing_track: Some(librespot_connect::PlayingTrack::Index( playing_track_index, )), }, )) .map_err(|e| MethodErr::failed(&e)) }); let local_state = current_state.clone(); b.property("PlaybackStatus") .emits_changed_false() .get(move |_, _| { let playback_state = local_state.read()?.status; Ok(playback_state.to_mpris().to_string()) }); let local_spirc = spirc.clone(); let local_state = current_state.clone(); b.property("Shuffle") .emits_changed_false() .get(move |_, _| Ok(local_state.read()?.shuffle)) .set(move |_, _, value| { local_spirc .shuffle(value) .map(|_| None) .map_err(|err| dbus::MethodErr::failed(&err)) }); b.property("Rate").emits_changed_const().get(|_, _| Ok(1.0)); b.property("MaximumRate") .emits_changed_const() .get(|_, _| Ok(1.0)); b.property("MinimumRate") .emits_changed_const() .get(|_, _| Ok(1.0)); let local_spirc = spirc.clone(); let local_state = current_state.clone(); b.property("Volume") .emits_changed_false() .get(move |_, _| Ok(local_state.read()?.mpris_volume())) .set(move |_, _, value| { if let Err(err) = local_spirc.set_volume((value * u16::MAX as f64) as u16) { return Err(dbus::MethodErr::failed(&err)); } Ok(None) }); let local_spirc = spirc.clone(); let local_state = current_state.clone(); b.property("LoopStatus") .emits_changed_true() .get(move |_, _| { let repeat = local_state.read()?.repeat; Ok(repeat.to_mpris().to_string()) }) .set(move |_, _, value| { let repeat = match value.as_str() { "None" => RepeatState::None, "Playlist" => RepeatState::All, "Track" => RepeatState::Track, mode => { return Err(dbus::MethodErr::failed(&format!( "unsupported repeat mode: {mode}" ))); } }; local_spirc .repeat(repeat.repeat_context()) .map_err(|e| MethodErr::failed(&e))?; local_spirc .repeat_track(repeat.repeat_track()) .map_err(|e| MethodErr::failed(&e))?; Ok(None) }); let local_state = current_state.clone(); b.property("Position") .emits_changed_false() .get(move |_, _| { let Some(position) = local_state.read()?.get_position() else { return Err(dbus::MethodErr::failed("no position available currently")); }; Ok(position.num_microseconds().unwrap_or_default()) }); let local_state = current_state.clone(); b.property("Metadata") .emits_changed_false() .get(move |_, _| Ok(local_state.read()?.to_metadata())); for prop in [ "CanPlay", "CanPause", "CanSeek", "CanControl", "CanGoPrevious", "CanGoNext", ] { b.property(prop).emits_changed_const().get(|_, _| Ok(true)); } }); cr.insert(MPRIS_PATH, &[media_player2_interface, player_interface], ()); seeked_signal.expect("player interface has not been registered") } fn register_controls_interface(cr: &mut Crossroads, spirc: Arc) { let spotifyd_ctrls_interface: IfaceToken<()> = cr.register("rs.spotifyd.Controls", |b| { let local_spirc = spirc.clone(); b.method("VolumeUp", (), (), move |_, _, (): ()| { local_spirc.volume_up().map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); b.method("VolumeDown", (), (), move |_, _, (): ()| { local_spirc.volume_down().map_err(|e| MethodErr::failed(&e)) }); let local_spirc = spirc.clone(); b.method("TransferPlayback", (), (), move |_, _, (): ()| { local_spirc.activate().map_err(|e| MethodErr::failed(&e)) }); }); cr.insert(CONTROLS_PATH, &[spotifyd_ctrls_interface], ()); } fn uri_to_object_path(uri: Option<&str>) -> dbus::Path<'static> { let Some(uri) = uri else { return dbus::Path::new("/org/mpris/MediaPlayer2/TrackList/NoTrack").unwrap(); }; let mut path = String::with_capacity(uri.len() + 1); for element in uri.split(':') { path.push('/'); path.push_str(element); } dbus::Path::new(path).unwrap() } ================================================ FILE: src/error.rs ================================================ use std::fmt::{self, Display}; /// This crate's error type. #[derive(Debug)] pub(crate) struct Error { kind: ErrorKind, } impl Error { pub(crate) fn subprocess(shell: &str, cmd: &str) -> Self { Self { kind: ErrorKind::Subprocess { cmd: cmd.into(), msg: Message::None, shell: shell.into(), }, } } pub(crate) fn subprocess_with_err(shell: &str, cmd: &str, e: E) -> Self where E: std::error::Error + 'static, { Self { kind: ErrorKind::Subprocess { cmd: cmd.into(), msg: Message::Error(Box::new(e)), shell: shell.into(), }, } } pub(crate) fn subprocess_with_str(shell: &str, cmd: &str, s: &str) -> Self { Self { kind: ErrorKind::Subprocess { cmd: cmd.into(), msg: Message::String(s.into()), shell: shell.into(), }, } } } impl From for Error { fn from(kind: ErrorKind) -> Self { Self { kind } } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.kind) } } impl std::error::Error for Error {} /// This crate's error kind type. #[derive(Debug)] pub(crate) enum ErrorKind { Subprocess { cmd: String, msg: Message, shell: String, }, #[allow(unused)] NormalisationPregainInvalid, } impl Display for ErrorKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ErrorKind::Subprocess { cmd, msg, shell } => match msg { Message::None => write!(f, "Failed to execute {cmd} using {shell}."), Message::Error(e) => { write!(f, "Failed to execute {cmd} using {shell}. Error: {e}",) } Message::String(s) => { write!(f, "Failed to execute {cmd} using {shell}. Error: {s}",) } }, ErrorKind::NormalisationPregainInvalid => write!( f, "normalisation-pregain must be a valid 32-bit floating point number." ), } } } #[derive(Debug)] pub(crate) enum Message { None, String(String), Error(Box), } ================================================ FILE: src/main.rs ================================================ use crate::config::CliConfig; use clap::Parser; #[cfg(unix)] use color_eyre::eyre::eyre; use color_eyre::eyre::{self, Context}; use config::ExecutionMode; #[cfg(unix)] use daemonize::Daemonize; use fern::colors::ColoredLevelConfig; use log::{LevelFilter, info, trace}; use oauth::run_oauth; #[cfg(target_os = "openbsd")] use pledge::pledge; #[cfg(windows)] use std::fs; use tokio::runtime::Runtime; #[cfg(feature = "alsa_backend")] mod alsa_mixer; mod config; #[cfg(feature = "dbus_mpris")] mod dbus_mpris; mod error; mod main_loop; mod no_mixer; mod oauth; mod process; mod setup; mod utils; enum LogTarget { Terminal, Syslog, } fn setup_logger(log_target: LogTarget, verbose: u8) -> eyre::Result<()> { let log_level = match verbose { 0 => LevelFilter::Info, 1 => LevelFilter::Debug, 2.. => LevelFilter::Trace, }; let mut logger = fern::Dispatch::new().level(log_level); if verbose == 0 { logger = logger.level_for("symphonia_format_ogg::demuxer", LevelFilter::Warn); } let logger = match log_target { LogTarget::Terminal => { let colors = ColoredLevelConfig::new(); logger .format(move |out, message, record| { let target = if verbose > 0 { &format!(" {}", record.target()) } else { "" }; out.finish(format_args!( "[{}{}] {}", colors.color(record.level()), target, message )) }) .chain(std::io::stdout()) } #[cfg(unix)] LogTarget::Syslog => { let log_format = syslog::Formatter3164 { facility: syslog::Facility::LOG_DAEMON, hostname: None, process: "spotifyd".to_owned(), pid: std::process::id(), }; logger.chain( syslog::unix(log_format) .map_err(|e| eyre!("Couldn't connect to syslog instance: {}", e))?, ) } #[cfg(target_os = "windows")] LogTarget::Syslog => { let dirs = directories::BaseDirs::new().unwrap(); let mut log_file = dirs.data_local_dir().to_path_buf(); log_file.push("spotifyd"); log_file.push(".spotifyd.log"); if let Some(p) = log_file.parent() { fs::create_dir_all(p)? }; logger.chain( fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .open(log_file) .expect("Couldn't initialize logger"), ) } }; logger.apply().wrap_err("Couldn't initialize logger") } fn main() -> eyre::Result<()> { // Start with superset of all potentially required promises. // Drop later after CLI arguments and configuration files were parsed. #[cfg(target_os = "openbsd")] pledge( "stdio rpath wpath cpath inet mcast flock chown unix dns proc exec audio", None, ) .unwrap(); color_eyre::install().wrap_err("Couldn't initialize error reporting")?; let cli_config = CliConfig::parse(); match cli_config.mode { None => run_daemon(cli_config), Some(ExecutionMode::Authenticate { oauth_port }) => run_oauth(cli_config, oauth_port), } } fn run_daemon(mut cli_config: CliConfig) -> eyre::Result<()> { let is_daemon = !cli_config.no_daemon; let log_target = if is_daemon { #[cfg(unix)] { LogTarget::Syslog } #[cfg(target_os = "windows")] { LogTarget::Terminal } } else { #[cfg(unix)] { LogTarget::Terminal } #[cfg(target_os = "windows")] { if std::env::var("SPOTIFYD_CHILD").is_ok() { LogTarget::Syslog } else { LogTarget::Terminal } } }; setup_logger(log_target, cli_config.verbose)?; cli_config .load_config_file_values() .wrap_err("could not load the config file")?; trace!("{:?}", &cli_config); // Returns the old SpotifydConfig struct used within the rest of the daemon. let internal_config = config::get_internal_config(cli_config); if is_daemon { info!("Daemonizing running instance"); #[cfg(unix)] { let mut daemonize = Daemonize::new(); if let Some(pid) = internal_config.pid.as_ref() { daemonize = daemonize.pid_file(pid); } match daemonize.start() { Ok(_) => info!("Detached from shell, now running in background."), Err(e) => return Err(e).wrap_err("something went wrong while daemonizing"), }; } #[cfg(target_os = "windows")] { use std::os::windows::process::CommandExt; use std::process::{Command, exit}; let mut args = std::env::args().collect::>(); args.remove(0); args.push("--no-daemon".to_string()); Command::new(std::env::current_exe().unwrap()) .args(args) .env("SPOTIFYD_CHILD", "1") .creation_flags(8 /* DETACHED_PROCESS */) .spawn() .expect("Couldn't spawn daemon"); exit(0); } } #[cfg(target_os = "openbsd")] { // At this point: // * --username-cmd, --password-cmd were handled // > no "proc exec" // * --pid, daemon(3) were handled // > no "cpath flock chown" for PID file // > no "proc" for double-fork(2) // // Required runtime promises: // stdout/err, syslog(3) "stdio" // ${TMPDIR}/.tmp*, cache "[rwc]path" // Spotify API/Connect "inet dns" // D-Bus, MPRIS "unix" // Zeroconf Discovery "mcast" // PortAudio, sio_open(3) ("[rwc]path unix inet audio") // > after sndio(7) cookie "audio" // --on-song-change-hook aka. "onevent", run via --shell aka. "shell" if internal_config.onevent.is_some() { pledge( "stdio rpath wpath cpath inet mcast unix dns proc exec audio", None, ) .unwrap(); } else { pledge("stdio rpath wpath cpath inet mcast unix dns audio", None).unwrap(); } } let runtime = Runtime::new().unwrap(); runtime.block_on(async { let initial_state = setup::initial_state(internal_config)?; initial_state.run().await }) } ================================================ FILE: src/main_loop.rs ================================================ #[cfg(feature = "dbus_mpris")] use crate::config::{DBusType, MprisConfig}; #[cfg(feature = "dbus_mpris")] use crate::dbus_mpris::DbusServer; use crate::process::spawn_program_on_event; use crate::utils::Backoff; use color_eyre::eyre::{self, Context}; use futures::future::Either; #[cfg(not(feature = "dbus_mpris"))] use futures::future::Pending; use futures::{ self, Future, FutureExt, StreamExt, future::{self, Fuse, FusedFuture}, stream::Peekable, }; use librespot_connect::{ConnectConfig, Spirc}; use librespot_core::{ Error, SessionConfig, authentication::Credentials, cache::Cache, config::DeviceType, session::Session, }; use librespot_discovery::Discovery; use librespot_playback::{ audio_backend::Sink, config::{AudioFormat, PlayerConfig}, mixer::Mixer, player::Player, }; use log::{error, info}; use std::pin::Pin; use std::sync::Arc; #[cfg(not(feature = "dbus_mpris"))] type DbusServer = Pending<()>; pub(crate) enum CredentialsProvider { Discovery { stream: Peekable, last_credentials: Option, }, CredentialsOnly(Credentials), } impl CredentialsProvider { async fn get_credentials(&mut self) -> Credentials { match self { CredentialsProvider::Discovery { stream, last_credentials, } => { let new_creds = match last_credentials.take() { Some(creds) => stream.next().now_or_never().flatten().unwrap_or(creds), None => stream.next().await.unwrap(), }; *last_credentials = Some(new_creds.clone()); new_creds } CredentialsProvider::CredentialsOnly(creds) => creds.clone(), } } // wait for an incoming connection if the underlying provider is a discovery stream async fn incoming_connection(&mut self) { match self { CredentialsProvider::Discovery { stream, .. } => { let peeked = Pin::new(stream).peek().await; if peeked.is_none() { future::pending().await } } _ => future::pending().await, } } } pub(crate) struct MainLoop { pub(crate) session_config: SessionConfig, pub(crate) player_config: PlayerConfig, pub(crate) cache: Option, pub(crate) mixer: Arc, pub(crate) backend: fn(Option, AudioFormat) -> Box, pub(crate) audio_device: Option, pub(crate) audio_format: AudioFormat, pub(crate) disable_volume: bool, pub(crate) initial_volume: u16, pub(crate) shell: String, pub(crate) device_type: DeviceType, pub(crate) device_name: String, pub(crate) player_event_program: Option, pub(crate) credentials_provider: CredentialsProvider, #[cfg(feature = "dbus_mpris")] pub(crate) mpris_config: MprisConfig, } struct ConnectionInfo> { spirc: Spirc, #[cfg_attr(not(feature = "dbus_mpris"), expect(unused))] session: Session, player: Arc, spirc_task: SpircTask, } impl MainLoop { async fn get_connection( &mut self, ) -> Result + use<>>, Error> { let creds = self.credentials_provider.get_credentials().await; let mut connection_backoff = Backoff::default(); loop { let session = Session::new(self.session_config.clone(), self.cache.clone()); let player = { let audio_device = self.audio_device.clone(); let audio_format = self.audio_format; let backend = self.backend; Player::new( self.player_config.clone(), session.clone(), self.mixer.get_soft_volume(), move || backend(audio_device, audio_format), ) }; // TODO: expose is_group match Spirc::new( ConnectConfig { name: self.device_name.clone(), device_type: self.device_type, initial_volume: self.initial_volume, disable_volume: self.disable_volume, ..ConnectConfig::default() }, session.clone(), creds.clone(), player.clone(), self.mixer.clone(), ) .await { Ok((spirc, spirc_task)) => { break Ok(ConnectionInfo { spirc, session, player, spirc_task, }); } Err(err) => { let Ok(backoff) = connection_backoff.next_backoff() else { break Err(err); }; error!("connection to spotify failed: {err}"); info!( "retrying connection in {} seconds (retry {}/{})", backoff.as_secs(), connection_backoff.retries(), connection_backoff.max_retries() ); tokio::time::sleep(backoff).await; } } } } pub(crate) async fn run(mut self) -> eyre::Result<()> { tokio::pin! { let ctrl_c = tokio::signal::ctrl_c(); // we don't necessarily have a dbus server let dbus_server = Either::::Right(future::pending()); } #[cfg(feature = "dbus_mpris")] let mpris_event_tx = if self.mpris_config.use_mpris.unwrap_or(true) { let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); *dbus_server.as_mut() = Either::Left(DbusServer::new( rx, self.mpris_config.dbus_type.unwrap_or(DBusType::Session), )); Some(tx) } else { None }; let mainloop_result: eyre::Result<()> = 'mainloop: loop { let connection = tokio::select!( _ = &mut ctrl_c => { break 'mainloop Ok(()); } connection = self.get_connection() => { match connection { Ok(connection) => connection, Err(err) => break 'mainloop Err(err).wrap_err("failed to connect to spotify"), } } ); let spirc_task = connection.spirc_task; tokio::pin!(spirc_task); let shared_spirc = Arc::new(connection.spirc); #[cfg(feature = "dbus_mpris")] if let Either::Left(mut dbus_server) = Either::as_pin_mut(dbus_server.as_mut()) && let Err(err) = dbus_server .as_mut() .set_session(shared_spirc.clone(), connection.session) { let _ = shared_spirc.shutdown(); let _ = (&mut spirc_task).await; break 'mainloop Err(err).wrap_err("failed to configure dbus server"); } let mut running_event_program = Box::pin(Fuse::terminated()); let mut event_channel = connection.player.get_player_event_channel(); loop { tokio::select!( // a new session has been started via the discovery stream _ = self.credentials_provider.incoming_connection() => { let _ = shared_spirc.shutdown(); let _ = (&mut spirc_task).await; break; } // the program should shut down _ = &mut ctrl_c => { let _ = shared_spirc.shutdown(); let _ = (&mut spirc_task).await; break 'mainloop Ok(()); } // spirc was shut down by some external factor _ = &mut spirc_task => { break; } // dbus stopped unexpectedly result = &mut dbus_server => { #[cfg(feature = "dbus_mpris")] { let _ = shared_spirc.shutdown(); let _ = (&mut spirc_task).await; *dbus_server.as_mut() = Either::Right(future::pending()); break 'mainloop result.wrap_err("DBus terminated unexpectedly"); } #[cfg(not(feature = "dbus_mpris"))] result // unused variable } // a new player event is available and no program is running event = event_channel.recv(), if running_event_program.is_terminated() => { let event = event.unwrap(); #[cfg(feature = "dbus_mpris")] if let Some(ref tx) = mpris_event_tx { tx.send(event.clone()).unwrap(); } if let Some(ref cmd) = self.player_event_program { match spawn_program_on_event(&self.shell, cmd, event) { Ok(child) => running_event_program = Box::pin(child.wait().fuse()), Err(e) => error!("{}", e), } } } // a running program has finished result = &mut running_event_program, if !running_event_program.is_terminated() => { match result { // Exited without error... Ok(_) => (), // Exited with error... Err(e) => error!("{}", e), } } ) } #[cfg(feature = "dbus_mpris")] if let Either::Left(dbus_server) = Either::as_pin_mut(dbus_server.as_mut()) && let Err(err) = dbus_server.drop_session() { break 'mainloop Err(err).wrap_err("failed to reconfigure DBus server"); } }; if let CredentialsProvider::Discovery { stream, .. } = self.credentials_provider { let _ = stream.into_inner().shutdown().await; } #[cfg(feature = "dbus_mpris")] if let Either::Left(dbus_server) = Either::as_pin_mut(dbus_server.as_mut()) && dbus_server.shutdown() && let Err(err) = dbus_server.await { let err = Err(err).wrap_err("failed to shutdown DBus server"); if mainloop_result.is_ok() { return err; } else { error!("additional error while shutting down: {err:?}"); } } mainloop_result } } ================================================ FILE: src/no_mixer.rs ================================================ use librespot_playback::mixer::{Mixer, MixerConfig}; pub struct NoMixer; impl Mixer for NoMixer { fn open(_: MixerConfig) -> Result { Ok(NoMixer {}) } fn volume(&self) -> u16 { u16::MAX } fn set_volume(&self, _volume: u16) {} } ================================================ FILE: src/oauth.rs ================================================ use color_eyre::{ Section as _, eyre::{self, Context as _}, }; use librespot_core::SessionConfig; use librespot_core::{Session, authentication::Credentials}; use librespot_oauth::OAuthClientBuilder; use log::info; use tokio::runtime::Runtime; use crate::{LogTarget, config::CliConfig, setup_logger}; pub(crate) fn run_oauth(mut cli_config: CliConfig, oauth_port: u16) -> eyre::Result<()> { setup_logger(LogTarget::Terminal, cli_config.verbose)?; cli_config .load_config_file_values() .wrap_err("failed to read config file")?; let cache = cli_config .shared_config .get_cache(true) .with_note(|| "The result of the authentication needs to be cached to be usable later.")?; const OAUTH_SCOPES: &[&str] = &[ "app-remote-control", "playlist-modify", "playlist-modify-private", "playlist-modify-public", "playlist-read", "playlist-read-collaborative", "playlist-read-private", "streaming", "ugc-image-upload", "user-follow-modify", "user-follow-read", "user-library-modify", "user-library-read", "user-modify", "user-modify-playback-state", "user-modify-private", "user-personalized", "user-read-birthdate", "user-read-currently-playing", "user-read-email", "user-read-play-history", "user-read-playback-position", "user-read-playback-state", "user-read-private", "user-read-recently-played", "user-top-read", ]; let session_config = SessionConfig { proxy: cli_config.shared_config.proxy_url(), ..Default::default() }; let oauth_client = OAuthClientBuilder::new( &session_config.client_id, &format!("http://127.0.0.1:{oauth_port}/login"), OAUTH_SCOPES.to_vec(), ) .with_custom_message(r#"

Authentication successful! You can now return to spotifyd.

"#) .open_in_browser() .build() .wrap_err("client creation failed")?; Runtime::new().unwrap().block_on(async move { let token = oauth_client.get_access_token_async().await?; let creds = Credentials::with_access_token(token.access_token); let session = Session::new(session_config, Some(cache)); session.connect(creds, true).await })?; info!("\nLogin successful! You are now ready to run spotifyd."); Ok(()) } ================================================ FILE: src/process.rs ================================================ use crate::error::Error; use librespot_metadata::audio::AudioItem; use librespot_playback::player::PlayerEvent; use log::info; use std::{collections::HashMap, process::Stdio}; use tokio::{ io::{self, AsyncWriteExt}, process::{self, Command}, }; /// Spawns provided command in a subprocess using the provided shell. fn spawn_program(shell: &str, cmd: &str, env: HashMap<&str, String>) -> Result { info!( "Running {:?} using {:?} with environment variables {:?}", cmd, shell, env ); let inner = Command::new(shell) .arg("-c") .arg(cmd) .envs(env.iter()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .map_err(|e| Error::subprocess_with_err(shell, cmd, e))?; let child = Child::new(cmd.to_string(), inner, shell.to_string()); Ok(child) } fn audio_item_to_env(audio_item: Box, env: &mut HashMap<&str, String>) { env.insert("TRACK_ID", audio_item.track_id.to_id().unwrap_or_default()); env.insert("TRACK_NAME", audio_item.name); env.insert("TRACK_DURATION", audio_item.duration_ms.to_string()); if let Some(cover) = audio_item.covers.into_iter().max_by_key(|c| c.width) { env.insert("TRACK_COVER", cover.url); } } /// Spawns provided command in a subprocess using the provided shell. /// Various environment variables are included in the subprocess's environment /// depending on the `PlayerEvent` that was passed in. pub(crate) fn spawn_program_on_event( shell: &str, cmd: &str, event: PlayerEvent, ) -> Result { let mut env = HashMap::new(); match event { PlayerEvent::TrackChanged { audio_item } => { env.insert("PLAYER_EVENT", "change".to_string()); audio_item_to_env(audio_item, &mut env); } PlayerEvent::Playing { track_id, play_request_id, position_ms, } => { env.insert("PLAYER_EVENT", "start".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); env.insert("POSITION_MS", position_ms.to_string()); } PlayerEvent::Stopped { track_id, play_request_id, } => { env.insert("PLAYER_EVENT", "stop".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } PlayerEvent::Loading { track_id, play_request_id, position_ms, } => { env.insert("PLAYER_EVENT", "load".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); env.insert("POSITION_MS", position_ms.to_string()); } PlayerEvent::Paused { track_id, play_request_id, position_ms, } => { env.insert("PLAYER_EVENT", "pause".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); env.insert("POSITION_MS", position_ms.to_string()); } PlayerEvent::TimeToPreloadNextTrack { track_id, play_request_id, } => { env.insert("PLAYER_EVENT", "preload".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } PlayerEvent::EndOfTrack { track_id, play_request_id, } => { env.insert("PLAYER_EVENT", "endoftrack".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } PlayerEvent::VolumeChanged { volume } => { env.insert("PLAYER_EVENT", "volumeset".to_string()); env.insert("VOLUME", volume.to_string()); } PlayerEvent::Unavailable { play_request_id, track_id, } => { env.insert("PLAYER_EVENT", "unavailable".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } PlayerEvent::Preloading { track_id } => { env.insert("PLAYER_EVENT", "preloading".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); } PlayerEvent::PositionCorrection { play_request_id, track_id, position_ms, } => { env.insert("PLAYER_EVENT", "positioncorrection".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("POSITION_MS", position_ms.to_string()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } PlayerEvent::Seeked { play_request_id, track_id, position_ms, } => { env.insert("PLAYER_EVENT", "seeked".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("POSITION_MS", position_ms.to_string()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } PlayerEvent::PlayRequestIdChanged { play_request_id } => { env.insert("PLAYER_EVENT", "playrequestid_changed".to_string()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } PlayerEvent::SessionConnected { connection_id, user_name, } => { env.insert("PLAYER_EVENT", "sessionconnected".to_string()); env.insert("USERNAME", user_name); env.insert("CONNECTION_ID", connection_id); } PlayerEvent::SessionDisconnected { connection_id, user_name, } => { env.insert("PLAYER_EVENT", "sessiondisconnected".to_string()); env.insert("USERNAME", user_name); env.insert("CONNECTION_ID", connection_id); } PlayerEvent::SessionClientChanged { client_id, client_name, client_brand_name, client_model_name, } => { env.insert("PLAYER_EVENT", "clientchanged".to_string()); env.insert("CLIENT_ID", client_id); env.insert("CLIENT_NAME", client_name); env.insert("CLIENT_BRAND", client_brand_name); env.insert("CLIENT_MODEL", client_model_name); } PlayerEvent::ShuffleChanged { shuffle } => { env.insert("PLAYER_EVENT", "shuffle_changed".to_string()); env.insert("SHUFFLE", shuffle.to_string()); } PlayerEvent::RepeatChanged { context, track } => { env.insert("PLAYER_EVENT", "repeat_changed".to_string()); let val = match context { true => match track { true => "track", false => "all", }, false => "none", } .to_string(); env.insert("REPEAT", val); } PlayerEvent::AutoPlayChanged { auto_play } => { env.insert("PLAYER_EVENT", "autoplay_changed".to_string()); env.insert("AUTOPLAY", auto_play.to_string()); } PlayerEvent::FilterExplicitContentChanged { filter } => { env.insert("PLAYER_EVENT", "filterexplicit_changed".to_string()); env.insert("FILTEREXPLICIT", filter.to_string()); } PlayerEvent::PositionChanged { play_request_id, position_ms, track_id, } => { env.insert("PLAYER_EVENT", "position_changed".to_string()); env.insert("TRACK_ID", track_id.to_id().unwrap()); env.insert("POSITION_MS", position_ms.to_string()); env.insert("PLAY_REQUEST_ID", play_request_id.to_string()); } } spawn_program(shell, cmd, env) } /// Wraps `tokio::process::Child` so that when this `Child` exits: /// * successfully: It writes the contents of it's stdout to the stdout of the /// main process. /// * unsuccesfully: It returns an error that includes the contents it's stderr /// as well as information on the command that was run and the shell that /// invoked it. pub(crate) struct Child { cmd: String, child: process::Child, shell: String, } impl Child { pub(crate) fn new(cmd: String, child: process::Child, shell: String) -> Self { Self { cmd, child, shell } } pub(crate) async fn wait(self) -> Result<(), Error> { let Child { cmd, shell, child } = self; let output = child .wait_with_output() .await .map_err(|e| Error::subprocess_with_err(&shell, &cmd, e))?; if output.status.success() { // If successful, write subprocess's stdout to main process's stdout... let mut stdout = io::stdout(); stdout .write_all(&output.stdout) .await .map_err(|e| Error::subprocess_with_err(&shell, &cmd, e))?; stdout .flush() .await .map_err(|e| Error::subprocess_with_err(&shell, &cmd, e))?; Ok(()) } else { // If unsuccessful, return an error that includes the contents of stderr... let err = match String::from_utf8(output.stderr) { Ok(stderr) => Error::subprocess_with_str(&shell, &cmd, &stderr), Err(_) => Error::subprocess(&shell, &cmd), }; Err(err) } } } ================================================ FILE: src/setup.rs ================================================ #[cfg(feature = "alsa_backend")] use crate::alsa_mixer; use crate::{ config, main_loop::{self, CredentialsProvider}, utils::Backoff, }; use color_eyre::{Section, eyre::eyre}; use futures::StreamExt as _; use librespot_playback::{ audio_backend::{self}, mixer::{self, Mixer, MixerConfig}, }; use log::{debug, error, info}; use std::{sync::Arc, thread}; pub(crate) fn initial_state( config: config::SpotifydConfig, ) -> color_eyre::Result { let mixer: Arc = { match config.volume_controller { config::VolumeController::None => { info!("Using no volume controller."); Arc::new(crate::no_mixer::NoMixer) } #[cfg(feature = "alsa_backend")] config::VolumeController::Alsa | config::VolumeController::AlsaLinear => { let device = config .alsa_config .mixer .as_deref() .or(config.audio_device.as_deref()) .unwrap_or("default") .to_string(); let control = config .alsa_config .control .as_deref() .unwrap_or("Master") .to_string(); info!("Using alsa volume controller."); use librespot_playback::config::VolumeCtrl; let volume_ctrl = if matches!( config.volume_controller, config::VolumeController::AlsaLinear ) { VolumeCtrl::Linear } else { VolumeCtrl::Log(0.0) /* this value is ignored */ }; Arc::new(alsa_mixer::AlsaMixer::open(MixerConfig { device, control, index: 0, volume_ctrl, }).with_suggestion(|| { match alsa_mixer::get_available_controls() { Err(err) => format!("there are no controls available, maybe check that alsa is available: {err}"), Ok(controls) => { format!("maybe try one of the following as 'mixer':{}", controls.filter_map(|hint| hint.name.map(|name| format!("\n- {name}"))).collect::()) } } })?) } _ => { info!("Using software volume controller."); let mixer = mixer::softmixer::SoftMixer::open(MixerConfig::default()) .expect("SoftMixer::open never returns an Error"); Arc::new(mixer) } } }; let player_config = config.player_config; let session_config = config.session_config; let backend = config.backend.clone(); let zeroconf_port = config.zeroconf_port.unwrap_or(0); let creds = if let Some(creds) = config.oauth_cache.as_ref().and_then(|c| c.credentials()) { info!( "Login via OAuth as user {}.", creds.username.as_deref().unwrap_or("unknown") ); Some(creds) } else if let Some(creds) = config.cache.as_ref().and_then(|c| c.credentials()) { info!( "Restoring previous login as user {}.", creds.username.as_deref().unwrap_or("unknown") ); Some(creds) } else { None }; let discovery = if config.discovery { info!("Starting zeroconf server to advertise on local network."); debug!("Using device id '{}'", session_config.device_id); let mut retry_backoff = Backoff::default(); loop { match librespot_discovery::Discovery::builder( session_config.device_id.clone(), session_config.client_id.clone(), ) .name(config.device_name.clone()) .device_type(config.device_type) .port(zeroconf_port) .launch() { Ok(discovery_stream) => break Some(discovery_stream), Err(err) => { error!("failed to enable discovery: {err}"); let Ok(backoff) = retry_backoff.next_backoff() else { error!("maximum amount of retries exceeded"); break None; }; info!("retrying discovery in {} seconds", backoff.as_secs()); thread::sleep(backoff); info!( "trying to enable discovery (retry {}/{})", retry_backoff.retries(), retry_backoff.max_retries() ); } } } } else { None }; let credentials_provider = match (discovery, creds) { (Some(stream), creds) => CredentialsProvider::Discovery { stream: stream.peekable(), last_credentials: creds, }, (None, Some(creds)) => CredentialsProvider::CredentialsOnly(creds), (None, None) => { return Err( eyre!("Discovery unavailable and no credentials found.").with_suggestion( || "Try enabling discovery or logging in first with `spotifyd authenticate`.", ), ); } }; let backend = audio_backend::find(backend).expect("available backends should match ours"); Ok(main_loop::MainLoop { credentials_provider, mixer, session_config, cache: config.cache, audio_device: config.audio_device, audio_format: config.audio_format, player_config, backend, initial_volume: config.initial_volume, disable_volume: false, shell: config.shell, device_type: config.device_type, device_name: config.device_name, player_event_program: config.onevent, #[cfg(feature = "dbus_mpris")] mpris_config: config.mpris, }) } ================================================ FILE: src/utils.rs ================================================ use log::trace; use std::{env, time::Duration}; #[cfg(any( target_os = "freebsd", target_os = "linux", target_os = "openbsd", target_os = "android" ))] fn get_shell_ffi() -> Option { use libc::{geteuid, getpwuid_r}; use std::{ffi::CStr, mem, ptr}; trace!("Retrieving user shell through libc calls"); let mut result = ptr::null_mut(); unsafe { let amt: usize = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) { n if n < 0 => 512, n => n as usize, }; let mut buf = Vec::with_capacity(amt); let mut passwd: libc::passwd = mem::zeroed(); match getpwuid_r( geteuid(), &mut passwd, buf.as_mut_ptr(), buf.capacity() as libc::size_t, &mut result, ) { 0 if !result.is_null() => { let ptr = passwd.pw_shell as *const _; let shell = CStr::from_ptr(ptr) .to_str() .expect("Failed to retrieve shell") .to_owned(); Some(shell) } _ => None, } } } // If the SHELL environment variable is not set and on we're on macOS, // query the Directory Service command line utility (dscl) for the user's shell, // as macOS does not use the /etc/passwd file #[cfg(target_os = "macos")] fn get_shell_ffi() -> Option { use std::process::Command; trace!("Retrieving user shell through Directory Discovery Services"); let username = whoami::username(); let output = Command::new("dscl") .args([".", "-read", &format!("/Users/{}", username), "UserShell"]) .output() .ok()?; if output.status.success() { let stdout = std::str::from_utf8(&output.stdout).ok()?; // The output of the dscl command should be: // "UserShell: /path/to/shell" if stdout.starts_with("UserShell: ") { let shell = stdout.split_whitespace().nth(1)?; return Some(shell.to_string()); } } None } #[cfg(target_os = "windows")] fn get_shell_ffi() -> Option { Some(String::from("cmd")) } pub(crate) fn get_shell() -> Option { let shell = env::var("SHELL").ok().or_else(get_shell_ffi); trace!("Found user shell: {:?}", &shell); shell } /// Implements basic exponential backoff. /// The used base is 2. pub(crate) struct Backoff { retry_counter: u8, max_retries: u8, initial_backoff: Duration, } impl Backoff { pub(crate) fn new(max_retries: u8, initial_backoff: Duration) -> Self { Self { retry_counter: 0, max_retries, initial_backoff, } } /// Get the next backoff duration. /// /// Increases the retry counter and returns the next required backoff duration, /// if available. pub(crate) fn next_backoff(&mut self) -> Result { if self.retry_counter >= self.max_retries { return Err(()); } let backoff_duration = self.initial_backoff * 2u32.pow(self.retry_counter as u32); self.retry_counter += 1; Ok(backoff_duration) } pub(crate) fn retries(&self) -> u8 { self.retry_counter } pub(crate) fn max_retries(&self) -> u8 { self.max_retries } } impl Default for Backoff { fn default() -> Self { Self::new(4, Duration::from_secs(5)) } } #[cfg(test)] mod tests { use super::*; fn init_logger() { let _ = env_logger::builder().is_test(true).try_init(); } #[test] fn test_envvar_discovery() { init_logger(); // SAFETY: this is part of the single-threaded tests unsafe { env::set_var("SHELL", "fantasy_shell"); } let shell = get_shell().unwrap(); assert_eq!(shell, "fantasy_shell"); } #[test] fn test_ffi_discovery() { init_logger(); let shell = get_shell_ffi(); assert!(shell.is_some()); } }