[
  {
    "path": ".all-contributorsrc",
    "content": "{\n  \"projectName\": \"spotifyd\",\n  \"projectOwner\": \"Spotifyd\",\n  \"repoType\": \"github\",\n  \"repoHost\": \"https://github.com\",\n  \"files\": [\n    \"CONTRIBUTORS.md\",\n    \"README.md\"\n  ],\n  \"imageSize\": 100,\n  \"commit\": true,\n  \"commitConvention\": \"angular\",\n  \"contributors\": [\n    {\n      \"login\": \"SirWindfield\",\n      \"name\": \"SirWindfield\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/5113257?v=4\",\n      \"profile\": \"https://github.com/SirWindfield\",\n      \"contributions\": [\n        \"code\",\n        \"doc\",\n        \"infra\",\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"0jdxt\",\n      \"name\": \"0jdxt\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/4650251?v=4\",\n      \"profile\": \"https://github.com/0jdxt\",\n      \"contributions\": [\n        \"code\",\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"bcmyers\",\n      \"name\": \"Brian Myers\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/10109972?v=4\",\n      \"profile\": \"https://github.com/bcmyers\",\n      \"contributions\": [\n        \"code\",\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"robinvd\",\n      \"name\": \"Robin\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/22073483?v=4\",\n      \"profile\": \"https://github.com/robinvd\",\n      \"contributions\": [\n        \"code\",\n        \"doc\",\n        \"infra\",\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"slondr\",\n      \"name\": \"Eric S. Londres\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/13040688?v=4\",\n      \"profile\": \"https://github.com/slondr\",\n      \"contributions\": [\n        \"code\",\n        \"doc\",\n        \"infra\",\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"mh84\",\n      \"name\": \"MH\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/17948500?v=4\",\n      \"profile\": \"https://github.com/mh84\",\n      \"contributions\": [\n        \"code\",\n        \"infra\"\n      ]\n    },\n    {\n      \"login\": \"valir\",\n      \"name\": \"Valentin Rusu\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/4358494?v=4\",\n      \"profile\": \"https://github.com/valir\",\n      \"contributions\": [\n        \"code\",\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"Mitschmaster\",\n      \"name\": \"Mitschmaster\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/39187239?v=4\",\n      \"profile\": \"https://github.com/Mitschmaster\",\n      \"contributions\": [\n        \"code\",\n        \"infra\"\n      ]\n    },\n    {\n      \"login\": \"zv0n\",\n      \"name\": \"zv0n\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/17143863?v=4\",\n      \"profile\": \"https://github.com/zv0n\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"Yarn\",\n      \"name\": \"Ryan\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/908816?v=4\",\n      \"profile\": \"https://github.com/Yarn\",\n      \"contributions\": [\n        \"code\",\n        \"infra\"\n      ]\n    },\n    {\n      \"login\": \"tommady\",\n      \"name\": \"tommady\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/11532828?v=4\",\n      \"profile\": \"https://tommady.com/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"newpavlov\",\n      \"name\": \"Artyom Pavlov\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/329626?v=4\",\n      \"profile\": \"https://github.com/newpavlov\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"popey\",\n      \"name\": \"Alan Pope\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/1841272?v=4\",\n      \"profile\": \"http://popey.com/\",\n      \"contributions\": [\n        \"platform\"\n      ]\n    },\n    {\n      \"login\": \"pfrenssen\",\n      \"name\": \"Pieter Frenssen\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/442924?v=4\",\n      \"profile\": \"https://github.com/pfrenssen\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"pstruschka\",\n      \"name\": \"Peter Son Struschka\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/10444945?v=4\",\n      \"profile\": \"https://github.com/pstruschka\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"nicokaiser\",\n      \"name\": \"Nico Kaiser\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/238631?v=4\",\n      \"profile\": \"https://kaiser.me/\",\n      \"contributions\": [\n        \"infra\"\n      ]\n    },\n    {\n      \"login\": \"JojiiOfficial\",\n      \"name\": \"JojiiOfficial\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/15957865?v=4\",\n      \"profile\": \"https://github.com/JojiiOfficial\",\n      \"contributions\": [\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"nkitan\",\n      \"name\": \"Ankit Das\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/32483252?v=4\",\n      \"profile\": \"https://github.com/nkitan\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"joelpet\",\n      \"name\": \"Joel Pettersson\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/114321?v=4\",\n      \"profile\": \"https://github.com/joelpet\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"juliangaal\",\n      \"name\": \"Julian Gaal\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/22290570?v=4\",\n      \"profile\": \"https://github.com/juliangaal\",\n      \"contributions\": [\n        \"doc\",\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"jackloughran\",\n      \"name\": \"Jack\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/30052269?v=4\",\n      \"profile\": \"https://github.com/jackloughran\",\n      \"contributions\": [\n        \"code\",\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"basvandenbrink\",\n      \"name\": \"Bas van den Brink\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/2811984?v=4\",\n      \"profile\": \"https://github.com/basvandenbrink\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"eisnerd\",\n      \"name\": \"David Eisner\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/441072?v=4\",\n      \"profile\": \"http://pph.me/david.eisner\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"stsydow\",\n      \"name\": \"Stefan Sydow\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/961256?v=4\",\n      \"profile\": \"http://metafly.info/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"TimotheeGerber\",\n      \"name\": \"Timothée Gerber\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/37541513?v=4\",\n      \"profile\": \"https://github.com/TimotheeGerber\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"maringuu\",\n      \"name\": \"Marten Ringwelski\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/60553448?v=4\",\n      \"profile\": \"https://github.com/maringuu\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"bertptrs\",\n      \"name\": \"Bert Peters\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/861864?v=4\",\n      \"profile\": \"https://bertptrs.nl/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"Calinou\",\n      \"name\": \"Hugo Locurcio\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/180032?v=4\",\n      \"profile\": \"https://hugo.pro/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"lulis\",\n      \"name\": \"Luiz Bettoni\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/6931166?v=4\",\n      \"profile\": \"http://odois.org/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"dcoppa\",\n      \"name\": \"dcoppa\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/1073526?v=4\",\n      \"profile\": \"https://github.com/dcoppa\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"andir\",\n      \"name\": \"Andreas Rammhold\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/638836?v=4\",\n      \"profile\": \"https://andreas.rammhold.de/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"jenting\",\n      \"name\": \"JenTing Hsiao\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/49380831?v=4\",\n      \"profile\": \"https://github.com/jenting\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"PontusPersson\",\n      \"name\": \"Pontus Persson\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/720546?v=4\",\n      \"profile\": \"https://pontus-persson.se/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"Jalle19\",\n      \"name\": \"Sam Stenvall\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/1106133?v=4\",\n      \"profile\": \"https://github.com/Jalle19\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"ashleytqy\",\n      \"name\": \"ashley teoh\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/11889765?v=4\",\n      \"profile\": \"https://ashleytqy.github.io/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"aksel\",\n      \"name\": \"aksel\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/6985716?v=4\",\n      \"profile\": \"https://github.com/aksel\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"sk22\",\n      \"name\": \"Samuel Kaiser\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/6217438?v=4\",\n      \"profile\": \"https://sk22.ml/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"smgt\",\n      \"name\": \"Simon Gate\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/2408?v=4\",\n      \"profile\": \"http://smgt.me/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"mattbailey\",\n      \"name\": \"Matt Bailey\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/216331?v=4\",\n      \"profile\": \"http://mdb.io/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"sflip\",\n      \"name\": \"Philipp Moers\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/6862899?v=4\",\n      \"profile\": \"https://philippmoers.de/\",\n      \"contributions\": [\n        \"code\",\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"Mange\",\n      \"name\": \"Magnus Bergmark\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/1599?v=4\",\n      \"profile\": \"https://github.com/Mange\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"Rik-de-Kort\",\n      \"name\": \"Rik-de-Kort\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/32839123?v=4\",\n      \"profile\": \"https://github.com/Rik-de-Kort\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"vringar\",\n      \"name\": \"Stefan Zabka\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/13276717?v=4\",\n      \"profile\": \"https://github.com/vringar\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"reschandreas\",\n      \"name\": \"Andreas Resch\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/16179620?v=4\",\n      \"profile\": \"https://github.com/reschandreas\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"marijnvanderhorst\",\n      \"name\": \"Marijn van der Horst\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/7057618?v=4\",\n      \"profile\": \"https://github.com/marijnvanderhorst\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"Jason-Cooke\",\n      \"name\": \"Jason Cooke\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/5185660?v=4\",\n      \"profile\": \"https://twitter.com/JSON_C11\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"codyshepherd\",\n      \"name\": \"Cody Shepherd\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/15008379?v=4\",\n      \"profile\": \"https://launchpad.net/~codyshepherd\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"bobvanderlinden\",\n      \"name\": \"Bob van der Linden\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/6375609?v=4\",\n      \"profile\": \"https://github.com/bobvanderlinden\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"pyrho\",\n      \"name\": \"Damien Rajon\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/145502?v=4\",\n      \"profile\": \"https://www.25.wf/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"awerlang\",\n      \"name\": \"André Werlang\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/589286?v=4\",\n      \"profile\": \"http://blog.werlangtecnologia.com.br/\",\n      \"contributions\": [\n        \"infra\"\n      ]\n    },\n    {\n      \"login\": \"timotk\",\n      \"name\": \"Timo\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/6358247?v=4\",\n      \"profile\": \"https://github.com/timotk\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"dimlev\",\n      \"name\": \"dimlev\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/1188269?v=4\",\n      \"profile\": \"https://github.com/dimlev\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"stuarth\",\n      \"name\": \"Stuart Hinson\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/7055?v=4\",\n      \"profile\": \"http://stuarth.github.io/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"bphermansson\",\n      \"name\": \"Patrik Hermansson\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/3775861?v=4\",\n      \"profile\": \"http://www.patrikhermansson.se/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"qaisjp\",\n      \"name\": \"Qais Patankar\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/923242?v=4\",\n      \"profile\": \"https://qaisjp.com/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"backspac\",\n      \"name\": \"backspac\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/8981640?v=4\",\n      \"profile\": \"https://github.com/backspac\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"WhyNotHugo\",\n      \"name\": \"Hugo Barrera\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/730811?v=4\",\n      \"profile\": \"https://hugo.barrera.io/\",\n      \"contributions\": [\n        \"platform\"\n      ]\n    },\n    {\n      \"login\": \"0xflotus\",\n      \"name\": \"0xflotus\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/26602940?v=4\",\n      \"profile\": \"https://github.com/0xflotus\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"wvangeit\",\n      \"name\": \"Werner Van Geit\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/3098670?v=4\",\n      \"profile\": \"https://github.com/wvangeit\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"ghishadow\",\n      \"name\": \"Suraj Ghimire\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/9583775?v=4\",\n      \"profile\": \"https://github.com/ghishadow\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"TobiMichael96\",\n      \"name\": \"Tobias Michael Effner\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/43846093?v=4\",\n      \"profile\": \"https://github.com/TobiMichael96\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"johnalanwoods\",\n      \"name\": \"Woodstock\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/5158898?v=4\",\n      \"profile\": \"https://github.com/johnalanwoods\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"ah-\",\n      \"name\": \"Andreas Heider\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/1349849?v=4\",\n      \"profile\": \"https://github.com/ah-\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"nickcorona\",\n      \"name\": \"Nick Corona\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/7490453?v=4\",\n      \"profile\": \"https://github.com/nickcorona\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"vickychenglau\",\n      \"name\": \"Vicky C Lau\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/22065437?v=4\",\n      \"profile\": \"https://github.com/vickychenglau\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"christopher-dG\",\n      \"name\": \"Chris de Graaf\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/17228795?v=4\",\n      \"profile\": \"https://github.com/christopher-dG\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"justin-gerhardt\",\n      \"name\": \"Justin Gerhardt\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/6844979?v=4\",\n      \"profile\": \"https://github.com/justin-gerhardt\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"wdehoog\",\n      \"name\": \"Willem-Jan de Hoog\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/3353303?v=4\",\n      \"profile\": \"https://github.com/wdehoog\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"CPerezz\",\n      \"name\": \"Carlos Pérez\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/37264926?v=4\",\n      \"profile\": \"https://github.com/CPerezz\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"RlndVt\",\n      \"name\": \"Roland Vet\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/1658570?v=4\",\n      \"profile\": \"https://github.com/RlndVt\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"Plecra\",\n      \"name\": \"Plecra\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/60934058?v=4\",\n      \"profile\": \"https://github.com/Plecra\",\n      \"contributions\": [\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"marcelbuesing\",\n      \"name\": \"Marcel\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/5637837?v=4\",\n      \"profile\": \"https://github.com/marcelbuesing\",\n      \"contributions\": [\n        \"code\",\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"izissise\",\n      \"name\": \"Hugues Morisset\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/2104672?v=4\",\n      \"profile\": \"https://github.com/izissise\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"katrielalex\",\n      \"name\": \"Katriel Cohn-Gordon\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/315959?v=4\",\n      \"profile\": \"http://www.katriel.co.uk/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"jb55\",\n      \"name\": \"William Casarin\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/45598?v=4\",\n      \"profile\": \"https://github.com/jb55\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"Gorzen\",\n      \"name\": \"Lucien Iseli\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/28461464?v=4\",\n      \"profile\": \"https://github.com/Gorzen\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"schnitzeltony\",\n      \"name\": \"Andreas Müller\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/2571823?v=4\",\n      \"profile\": \"https://github.com/schnitzeltony\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"Crazybus\",\n      \"name\": \"Michael Russell\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/4550136?v=4\",\n      \"profile\": \"https://michaelrussell.ninja/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"metiis\",\n      \"name\": \"Julia\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/31927016?v=4\",\n      \"profile\": \"https://github.com/metiis\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"aignas\",\n      \"name\": \"Ignas Anikevicius\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/240938?v=4\",\n      \"profile\": \"http://anikevicius.lt/\",\n      \"contributions\": [\n        \"infra\",\n        \"doc\",\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"Ben-PH\",\n      \"name\": \"Ben\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/16680090?v=4\",\n      \"profile\": \"https://github.com/Ben-PH\",\n      \"contributions\": [\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"MarinPostma\",\n      \"name\": \"marin\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/28804882?v=4\",\n      \"profile\": \"https://github.com/MarinPostma\",\n      \"contributions\": [\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"SimonPersson\",\n      \"name\": \"Simon Persson\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/606973?v=4\",\n      \"profile\": \"https://github.com/SimonPersson\",\n      \"contributions\": [\n        \"maintenance\",\n        \"doc\",\n        \"code\",\n        \"infra\"\n      ]\n    }\n  ],\n  \"contributorsPerLine\": 7,\n  \"contributorsSortAlphabetically\": true\n}\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**Description**\n<!-- A clear and concise description of what the bug is -->\n\n**To Reproduce**\n<!-- Steps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error -->\n\n**Expected behavior**\n<!-- A clear and concise description of what you expected to happen (if applicable) -->\n\n**Logs**\n<details><summary>Click to show logs</summary>\n\n```\n<!-- PLEASE PASTE YOUR LOGS BELOW THIS LINE WHEN REPORTING BUGS. Make sure to run spotifyd using the `--verbose` flag -->\n<!-- They have to be betwenn the `/summary` and the `/details` HTML tags, and inside the backticks '`' -->  \n```\n\n</details>\n\n<!-- if you compiled spotifyd yourself. Alsa backend enabled by default unless compiled with the `--no-default-features` flag -->\n**Compilation flags** \n- [ ] dbus_mpris\n- [x] alsa_backend\n- [ ] portaudio_backend\n- [ ] pulseaudio_backend\n- [ ] rodio_backend\n\n**Versions (please complete the following information):**\n<!-- DO NOT use words like `latest`. Please specify the exact version/commit hash -->\n- OS: <!-- e.g. Ubuntu 18.04 LTS, Windows 10 -->\n- Spotifyd: <!-- commit hash or release version -->\n- cargo: <!-- cargo --version -->\n\n<!-- **Additional context**\nAdd any other context about the problem here. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: General questions and support\n    url: https://matrix.to/#/#spotifyd:matrix.org\n    about: You can also reach us via matrix and ask your questions regarding spotifyd there.\n  - name: Other\n    url: https://github.com/Spotifyd/spotifyd/discussions/new/choose\n    about: For other requests, consider creating a discussion.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n<!-- **Additional context**\nAdd any other context or screenshots about the feature request here. -->\n"
  },
  {
    "path": ".github/workflows/cd.yml",
    "content": "name: Continuous Deployment\n\non:\n  push:\n    branches:\n      - master\n    tags:\n      - 'v*.*.*'\n\njobs:\n  build:\n    name: Building ${{matrix.os}}-${{ matrix.arch }} (${{ matrix.artifact_type }})\n    runs-on: ${{ matrix.runs_on }}\n    strategy:\n      matrix:\n        os: [macos, linux]\n        arch: [x86_64, aarch64, armv7]\n        rust: [stable]\n        artifact_type: ['slim', 'default', 'full']  # The build strategy will build all types for each OS specified\n        include:\n          # Runner configuration\n          - os: macos\n            arch: x86_64\n            runs_on: macos-15-intel\n          - os: macos\n            arch: aarch64\n            runs_on: macos-15\n          - os: linux\n            runs_on: ubuntu-22.04\n          - os: linux\n            arch: aarch64\n            runs_on: ubuntu-22.04-arm\n          # DBus configuration\n          - artifact_type: slim\n            dbus: ''\n          - artifact_type: default\n            dbus: dbus_mpris\n          - artifact_type: full\n            dbus: dbus_mpris\n          # Cross Compilation Targets\n          - os: linux\n            arch: armv7\n            target: armv7-unknown-linux-gnueabihf\n          # Audio backend configuration: Linux\n          - os: linux\n            artifact_type: slim\n            audio_backends: alsa_backend\n          - os: linux\n            artifact_type: default\n            audio_backends: alsa_backend,pulseaudio_backend,rodio_backend\n          - os: linux\n            artifact_type: full\n            audio_backends: alsa_backend,pulseaudio_backend,rodio_backend,rodiojack_backend\n          # Audio backend configuration: macOS\n          - os: macos\n            audio_backends: portaudio_backend,rodio_backend\n        exclude:\n          - os: macos\n            artifact_type: 'full'\n          - os: macos\n            arch: armv7\n    steps:\n      - name: Checking out sources\n        uses: actions/checkout@v4\n      - name: Installing needed macOS dependencies\n        if: matrix.os == 'macos'\n        run: brew install dbus portaudio\n      - name: Installing needed Ubuntu dependencies\n        if: startsWith(matrix.runs_on, 'ubuntu') && matrix.target == ''\n        run: |\n          sudo apt-get update\n          # WORKAROUND: fix aws-lc-sys compiler bug failure\n          sudo apt-get remove -y gcc-9\n          sudo apt-get install -y gcc-10\n          echo \"CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=gcc-10\" >> \"$GITHUB_ENV\"\n          echo \"CC=gcc-10\" >> \"$GITHUB_ENV\"\n          # alsa_backend,rodio_backend and base deps\n          sudo apt-get install -y libasound2-dev libssl-dev\n          # dbus_mpris\n          sudo apt-get install -y libdbus-1-dev\n          # pulseaudio_backend\n          sudo apt-get install -y libpulse-dev\n          # portaudio_backend\n          sudo apt-get install -y portaudio19-dev\n      - name: Determine cargo args\n        run: |\n          features=\"--no-default-features --features ${{ matrix.dbus }},${{ matrix.audio_backends }}\"\n          echo CARGO_ARGS=\"--locked --release $features\" | tee -a \"$GITHUB_ENV\"\n      - name: Build (using cargo)\n        if: matrix.target == ''\n        run: |\n           cargo +${{ matrix.rust }} build $CARGO_ARGS\n      - name: Build (using cross)\n        if: matrix.target != ''\n        uses: houseabsolute/actions-rust-cross@v1\n        with:\n          cross-version: baf457e # currently needed (check again if cross version > 0.2.5)\n          command: build\n          toolchain: ${{ matrix.rust }}\n          target: ${{ matrix.target }}\n          args: $CARGO_ARGS\n      - name: Uploading artifacts\n        uses: actions/upload-artifact@v4\n        with:\n          name: spotifyd-${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.artifact_type }}\n          path: target/${{ matrix.target }}/release/spotifyd\n  release: # only runs when a version tag is pushed\n    if: startsWith(github.ref, 'refs/tags/v')\n    needs: build\n    runs-on: ubuntu-latest\n    steps:\n      - name: Downloading artifacts # download all binaries\n        uses: actions/download-artifact@v4\n      - name: Packaging final binary\n        shell: bash\n        run: |\n          for artifact_dir in ./*/\n          do\n            pushd $artifact_dir\n            artifact_name=$(basename $artifact_dir)\n            tar czvf $artifact_name.tar.gz spotifyd\n            shasum -a 512 $artifact_name.tar.gz > $artifact_name.sha512\n            popd\n          done\n      - name: Releasing assets\n        uses: softprops/action-gh-release@v1\n        with:\n          files: |\n            **/*.tar.gz\n            **/*.sha512\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: Continuous Integration\n\non:\n  pull_request:\n    paths:\n      - '**.rs'\n      - 'Cargo.toml'\n      - 'Cargo.lock'\n      - 'contrib/spotifyd.conf'\n\njobs:\n  codestyle:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Installing Rust toolchain\n        uses: actions-rs/toolchain@v1\n        with:\n          toolchain: stable\n          override: true\n      - name: Checking out sources\n        uses: actions/checkout@v1\n      - name: Installing rustfmt\n        run: rustup component add rustfmt\n      - name: Running rustfmt\n        uses: actions-rs/cargo@v1\n        with:\n          command: fmt\n          args: -- --check\n\n  lint:\n    needs: [codestyle]\n    runs-on: ubuntu-latest\n    steps:\n      - name: Installing Rust toolchain\n        uses: actions-rs/toolchain@v1\n        with:\n          toolchain: stable\n          override: true\n      - name: Installing needed Ubuntu dependencies\n        run: |\n          sudo apt-get update\n          sudo apt-get install -y -qq libasound2-dev libssl-dev libpulse-dev libdbus-1-dev portaudio19-dev\n\n      - name: Checking out sources\n        uses: actions/checkout@v1\n      - name: Installing clippy\n        run: rustup component add clippy\n      - name: Linting project\n        uses: actions-rs/cargo@v1\n        with:\n          command: clippy\n          args: --all-targets --all-features -- -D warnings\n\n  test:\n    needs: [lint]\n    runs-on: ${{ matrix.os }}\n    strategy:\n      matrix:\n        rust: [stable, 1.88]\n        os: [macos-latest, ubuntu-latest]\n        include:\n          - os: macos-latest\n            features: portaudio_backend,rodio_backend\n          - os: ubuntu-latest\n            features: alsa_backend,rodio_backend,dbus_mpris\n\n    steps:\n      - name: Installing Rust toolchain\n        uses: actions-rs/toolchain@v1\n        with:\n          toolchain: ${{ matrix.rust }}\n          override: true\n      - name: Installing macOS dependencies\n        if: matrix.os == 'macos-latest'\n        run: brew install pkg-config portaudio\n      - name: Installing needed Ubuntu dependencies\n        if: matrix.os == 'ubuntu-latest'\n        run: |\n          sudo apt-get update\n          sudo apt-get install -y -qq libasound2-dev libssl-dev libpulse-dev libdbus-1-dev\n\n      - name: Checking out sources\n        uses: actions/checkout@v1\n      - name: Checking Rust code\n        uses: actions-rs/cargo@v1\n        with:\n          command: test\n          args: --locked --no-default-features --features ${{ matrix.features }}\n"
  },
  {
    "path": ".github/workflows/docs.yml",
    "content": "name: Continuous Integration - Docs\n\non:\n  # Runs on pushes targeting the default branch\n  push:\n    branches: [\"master\"]\n    paths:\n      - .github/workflows/docs.yml\n      - docs/**\n\n  # Allows you to run this workflow manually from the Actions tab\n  workflow_dispatch:\n\n# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages\npermissions:\n  contents: read\n  pages: write\n  id-token: write\n\n# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.\n# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.\nconcurrency:\n  group: \"pages\"\n  cancel-in-progress: false\n\njobs:\n  # Build job\n  build:\n    runs-on: ubuntu-latest\n    env:\n      MDBOOK_VERSION: 0.4.45\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install mdBook\n        run: |\n          curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf -y | sh\n          rustup update\n          cargo install --version ${MDBOOK_VERSION} mdbook\n      - name: Setup Pages\n        id: pages\n        uses: actions/configure-pages@v3\n      - name: Build with mdBook\n        run: mdbook build ./docs\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v3\n        with:\n          path: ./docs/book\n\n  # Deployment job\n  deploy:\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    needs: build\n    steps:\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v4\n"
  },
  {
    "path": ".gitignore",
    "content": "\n# Created by https://www.gitignore.io/api/vim,rust\n\n### Vim ###\n# swap\n[._]*.s[a-v][a-z]\n[._]*.sw[a-p]\n[._]s[a-v][a-z]\n[._]sw[a-p]\n# session\nSession.vim\n# temporary\n.netrwhist\n*~\n# auto-generated tag files\ntags\n\n\n### Rust ###\n# Generated by Cargo\n# will have compiled files and executables\n/target/\n\n# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries\n# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock\n#Cargo.lock\n\n# These are backup files generated by rustfmt\n**/*.rs.bk\n\n# End of https://www.gitignore.io/api/vim,rust\n\n*.rustfmt\n\n.idea\n.vscode\n# Windows logs\n*.log\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [Unreleased]\n\n## [0.4.2]\n\n### Fixed\n- fix multiple playback issues introduced by Spotify changes ([#1362], [#1374])\n- fix crash on user switch ([#1361])\n\n### Added\n- add suggestions for alsa mixer / control device names\n- improve distribution support for Debian and Fedora ([#1364], [#1372])\n\n[#1361]: https://github.com/Spotifyd/spotifyd/pull/1361\n[#1362]: https://github.com/Spotifyd/spotifyd/pull/1362\n[#1364]: https://github.com/Spotifyd/spotifyd/pull/1364\n[#1372]: https://github.com/Spotifyd/spotifyd/pull/1372\n[#1374]: https://github.com/Spotifyd/spotifyd/pull/1374\n\n## [0.4.1]\n\n### Fixed\n- revert default features to `alsa_backend` ([#1337])\n- do not require `bindgen` dependencies on supported systems ([#1340])\n- always return exitcode 1 on error ([#1338])\n- the released binaries for `linux-x86_64` also work for older systems ([#1342])\n\n[#1337]: https://github.com/Spotifyd/spotifyd/pull/1337\n[#1338]: https://github.com/Spotifyd/spotifyd/pull/1338\n[#1340]: https://github.com/Spotifyd/spotifyd/pull/1340\n[#1342]: https://github.com/Spotifyd/spotifyd/pull/1342\n\n## [0.4.0]\n\n### Breaking\n- username and password authentaction have been removed and are replaced by OAuth ([#1321])\n  Look at the [docs](https://docs.spotifyd.rs/) for setup instructions.\n\n### Added\n- retry enabling discovery several times before exiting ([#1228])\n- development artifacts are now available ([#1332])\n- prebuilt binaries are available for `aarch64` (both Linux and macOS) ([#1332])\n- Windows and Android are now supported ([#1219], [#1314])\n- expose pipe and subprocess backends ([#1284])\n- new device type options are available ([#1316])\n- OAuth login is now supported ([#1321])\n- a warning is emitted on unsupported configuration values ([#1327])\n\n### Changed\n- the docs have been overhauled to reflect the current state of the project and simplify onboarding ([#1327])\n- `librespot` dependency has been updated to 0.6 ([#1317])\n- Credential caching has been re-enabled. ([#1214])\n\n### Fixed\n- alsa mixer: volume calculation has been fixed ([#1229])\n\n### Removed\n- `armv6` binaries are no longer available by default ([#1332])\n  If you still need them, please join our matrix channel (https://matrix.to/#/#spotifyd:matrix.org) and tell us!\n\n[#1214]: https://github.com/Spotifyd/spotifyd/pull/1214\n[#1229]: https://github.com/Spotifyd/spotifyd/pull/1229\n[#1228]: https://github.com/Spotifyd/spotifyd/pull/1228\n[#1284]: https://github.com/Spotifyd/spotifyd/pull/1284\n[#1219]: https://github.com/Spotifyd/spotifyd/pull/1219\n[#1314]: https://github.com/Spotifyd/spotifyd/pull/1314\n[#1316]: https://github.com/Spotifyd/spotifyd/pull/1316\n[#1317]: https://github.com/Spotifyd/spotifyd/pull/1317\n[#1321]: https://github.com/Spotifyd/spotifyd/pull/1321\n[#1327]: https://github.com/Spotifyd/spotifyd/pull/1327\n[#1332]: https://github.com/Spotifyd/spotifyd/pull/1332\n\n## [0.3.5]\n\nWe now have a [project website](https://spotifyd.rs) (thanks @slondr!) and a [matrix room](https://matrix.to/#/#spotifyd:matrix.org).\nFeel free to join and ask your questions!\n\n### Added\n- `TransferPlayback` D-Bus method to transfer the playback to `spotifyd` ([#1162])\n  To host this, a `rs.spotifyd.Controls` interface has been added.\n- A `audio_format` option was added to circumvent certain errors ([#1082])\n- A setter was added to the `Shuffle` property ([#1188])\n- `volume_control = \"none\"` variant to disable changing the volume in clients ([#750])\n### Changed\n- Improve backend selection logic, especially for macOS ([#1158])\n- Update `keyring` dependency to newest version ([#1174])\n- `VolumeUp`, `VolumeDown` D-Bus methods have been copied to spotifyd's controls interface ([#1162])\n  Their versions in `org.mpris.MediaPlayer2.Player` have been deprecated and will be removed in a breaking release.\n- The `librespot` dependency has been upgraded to the most recent release 🎉 ([#1182], [#1197])\n- Many other dependency updates ([#1183], [#1145], [#1199])\n- Documentation improvements ([#1156])\n- Our minimum supported rust version (MSRV) has been bumped to 1.64 ([#1145])\n\n[#750]: https://github.com/Spotifyd/spotifyd/pull/750\n[#1082]: https://github.com/Spotifyd/spotifyd/pull/1082\n[#1145]: https://github.com/Spotifyd/spotifyd/pull/1145\n[#1156]: https://github.com/Spotifyd/spotifyd/pull/1156\n[#1158]: https://github.com/Spotifyd/spotifyd/pull/1158\n[#1162]: https://github.com/Spotifyd/spotifyd/pull/1162\n[#1174]: https://github.com/Spotifyd/spotifyd/pull/1174\n[#1182]: https://github.com/Spotifyd/spotifyd/pull/1182\n[#1183]: https://github.com/Spotifyd/spotifyd/pull/1183\n[#1188]: https://github.com/Spotifyd/spotifyd/pull/1188\n[#1197]: https://github.com/Spotifyd/spotifyd/pull/1197\n[#1199]: https://github.com/Spotifyd/spotifyd/pull/1199\n\n## [0.3.4]\n### Added \n- Implement the `PropertiesChanged` and `Seeked` events for the MPRIS-interface ([#1025])\n- Add `cache_size` configuration option ([#1092])\n- Add `dbus_type` configuration option ([#954])\n- Added formal documentation of the minimum required Rust version - which is currently 1.62 ([#1127])\n### Changed\n- Improvements to the documentation ([#894], [#955], [#1030], [#1039], [#1054], [#1055], [#1067])\n- Fix cumulating delay in `on_song_change_hook` ([#1059])\n- Only enable one of zeroconf discovery and password-authentication at the same time ([#1059])\n- Convert mainloop to using `async` / `await` ([#1059])\n- Upgrade `rspotify` dependency to `0.11.5` ([#1079])\n- Improve error reporting ([#1108])\n- Make `spotifyd` bus name unique ([#1100])  \n  **Note:** If you were relying on the consistent bus name of `org.mpris.MediaPlayer2.spotifyd`,\n  you can adapt your script e.g. by querying the name like `qdbus | grep \"org.mpris.MediaPlayer2.spotifyd\"`\n- Fix wrong handling of credential cache ([#1121])\n### Removed\n- Replace redundant `reqwest` dependency ([#1120])\n\n[#894]: https://github.com/Spotifyd/spotifyd/pull/894\n[#954]: https://github.com/Spotifyd/spotifyd/pull/954\n[#955]: https://github.com/Spotifyd/spotifyd/pull/955\n[#1025]: https://github.com/Spotifyd/spotifyd/pull/1025\n[#1030]: https://github.com/Spotifyd/spotifyd/pull/1030\n[#1039]: https://github.com/Spotifyd/spotifyd/pull/1039\n[#1054]: https://github.com/Spotifyd/spotifyd/pull/1054\n[#1055]: https://github.com/Spotifyd/spotifyd/pull/1055\n[#1059]: https://github.com/Spotifyd/spotifyd/pull/1059\n[#1067]: https://github.com/Spotifyd/spotifyd/pull/1067\n[#1079]: https://github.com/Spotifyd/spotifyd/pull/1079\n[#1092]: https://github.com/Spotifyd/spotifyd/pull/1092\n[#1100]: https://github.com/Spotifyd/spotifyd/pull/1100\n[#1108]: https://github.com/Spotifyd/spotifyd/pull/1108\n[#1120]: https://github.com/Spotifyd/spotifyd/pull/1120\n[#1121]: https://github.com/Spotifyd/spotifyd/pull/1120\n\n## [0.3.3]\n### Added \n- Add `debug_credentials` feature for debugging `BadCredentials` errors [#915]\n- Implement `VolumeUp` and `VolumeDown` in the DBUS/MPRIS interface [#963]\n- Update librespot to 0.2.0 [#977]\n- Rewrite DBUS/MPRIS integration [#977]\n### Changed\n- Improved panic error message [#925]\n### Removed\n\n[#915]: https://github.com/Spotifyd/spotifyd/pull/915\n[#925]: https://github.com/Spotifyd/spotifyd/pull/925\n[#963]: https://github.com/Spotifyd/spotifyd/pull/963\n[#977]: https://github.com/Spotifyd/spotifyd/pull/977\n\n## [0.3.1]\n### Added \n- Use eyre for better error reporting [#789]\n- Add a contributers file\n\n### Changed\n- Change docs from readme to mkdocs [#783]\n- Update librespot, thus fixing [#719] [#900]\n### Removed\n\n[#789]: https://github.com/Spotifyd/spotifyd/pull/789\n[#783]: https://github.com/Spotifyd/spotifyd/pull/783\n[#719]: https://github.com/Spotifyd/spotifyd/issues/719\n[#900]: https://github.com/Spotifyd/spotifyd/pull/900\n## [0.3.0]\n### Added\n- Added a changelog [#714]\n### Changed\n- Changed the config format from ini to TOML [#571]\n\n[#571]: https://github.com/Spotifyd/spotifyd/pull/571\n[#714]: https://github.com/Spotifyd/spotifyd/pull/714\n### Removed\n\n## [0.2.24]\n\n[Unreleased]: https://github.com/Spotifyd/spotifyd/compare/v0.4.2...HEAD\n[0.4.2]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.4.2\n[0.4.1]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.4.1\n[0.4.0]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.4.0\n[0.3.5]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.5\n[0.3.4]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.4\n[0.3.3]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.3\n[0.3.1]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.1\n[0.3.0]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.3.0\n[0.2.24]: https://github.com/Spotifyd/spotifyd/releases/tag/v0.2.24\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\n## Setup\n\n__Important:__ Make sure to install the provided git hooks by running `setup-dev-workspace.sh`! \n\n### Install Rust\n\nIt 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.\n\n### Install rustfmt and clippy\n\n```sh\nrustup component add rustfmt\nrustup component add clippy\n```\n\n### External Dependencies\n\nThe 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.\n\nOther 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].\n\n## Building and Running the project\n\nTo run spotifyd with the rodio backend run\n\n```sh\ncargo run --features rodio_backend --no-default-features  -- --backend rodio --no-daemon\n```\n\nSee the readme for information on setting up a config file and what features are available.\n\n## Contributing Code\n\nNote that spotifyd uses `Cargo.lock` to track dependency versions. It shouldn't be changed unless you are intentionally bumping a dependency version.\n\nCheck your code with `rustfmt` and `clippy`.\n\n```sh\ncargo fmt -- --check\ncargo clippy --no-default-features --features rodio_backend -- -D warnings\n```\n\nCI will run `clippy --all-targets --all-features -- -D warnings` but this requires having dependencies for all features installed.\n\nCreate a PR on github.\n"
  },
  {
    "path": "CONTRIBUTORS.md",
    "content": "\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/0jdxt\"><img src=\"https://avatars.githubusercontent.com/u/4650251?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>0jdxt</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=0jdxt\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=0jdxt\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/0xflotus\"><img src=\"https://avatars.githubusercontent.com/u/26602940?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>0xflotus</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=0xflotus\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"http://popey.com/\"><img src=\"https://avatars.githubusercontent.com/u/1841272?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Alan Pope</b></sub></a><br /><a href=\"#platform-popey\" title=\"Packaging/porting to new platform\">📦</a></td>\n    <td align=\"center\"><a href=\"https://github.com/ah-\"><img src=\"https://avatars.githubusercontent.com/u/1349849?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Andreas Heider</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=ah-\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/schnitzeltony\"><img src=\"https://avatars.githubusercontent.com/u/2571823?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Andreas Müller</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=schnitzeltony\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://andreas.rammhold.de/\"><img src=\"https://avatars.githubusercontent.com/u/638836?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Andreas Rammhold</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=andir\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/reschandreas\"><img src=\"https://avatars.githubusercontent.com/u/16179620?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Andreas Resch</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=reschandreas\" title=\"Code\">💻</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"http://blog.werlangtecnologia.com.br/\"><img src=\"https://avatars.githubusercontent.com/u/589286?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>André Werlang</b></sub></a><br /><a href=\"#infra-awerlang\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n    <td align=\"center\"><a href=\"https://github.com/nkitan\"><img src=\"https://avatars.githubusercontent.com/u/32483252?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Ankit Das</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=nkitan\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/newpavlov\"><img src=\"https://avatars.githubusercontent.com/u/329626?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Artyom Pavlov</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=newpavlov\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/basvandenbrink\"><img src=\"https://avatars.githubusercontent.com/u/2811984?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Bas van den Brink</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=basvandenbrink\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/Ben-PH\"><img src=\"https://avatars.githubusercontent.com/u/16680090?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Ben</b></sub></a><br /><a href=\"#maintenance-Ben-PH\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"https://bertptrs.nl/\"><img src=\"https://avatars.githubusercontent.com/u/861864?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Bert Peters</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=bertptrs\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/bobvanderlinden\"><img src=\"https://avatars.githubusercontent.com/u/6375609?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Bob van der Linden</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=bobvanderlinden\" title=\"Code\">💻</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/bcmyers\"><img src=\"https://avatars.githubusercontent.com/u/10109972?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Brian Myers</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=bcmyers\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=bcmyers\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/CPerezz\"><img src=\"https://avatars.githubusercontent.com/u/37264926?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Carlos Pérez</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=CPerezz\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/christopher-dG\"><img src=\"https://avatars.githubusercontent.com/u/17228795?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Chris de Graaf</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=christopher-dG\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://launchpad.net/~codyshepherd\"><img src=\"https://avatars.githubusercontent.com/u/15008379?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Cody Shepherd</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=codyshepherd\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://www.25.wf/\"><img src=\"https://avatars.githubusercontent.com/u/145502?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Damien Rajon</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=pyrho\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"http://pph.me/david.eisner\"><img src=\"https://avatars.githubusercontent.com/u/441072?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>David Eisner</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=eisnerd\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/slondr\"><img src=\"https://avatars.githubusercontent.com/u/13040688?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Eric S. Londres</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=slondr\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=slondr\" title=\"Documentation\">📖</a> <a href=\"#infra-slondr\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a> <a href=\"#maintenance-slondr\" title=\"Maintenance\">🚧</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://hugo.barrera.io/\"><img src=\"https://avatars.githubusercontent.com/u/730811?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Hugo Barrera</b></sub></a><br /><a href=\"#platform-WhyNotHugo\" title=\"Packaging/porting to new platform\">📦</a></td>\n    <td align=\"center\"><a href=\"https://hugo.pro/\"><img src=\"https://avatars.githubusercontent.com/u/180032?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Hugo Locurcio</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Calinou\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/izissise\"><img src=\"https://avatars.githubusercontent.com/u/2104672?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Hugues Morisset</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=izissise\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"http://anikevicius.lt/\"><img src=\"https://avatars.githubusercontent.com/u/240938?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Ignas Anikevicius</b></sub></a><br /><a href=\"#infra-aignas\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=aignas\" title=\"Documentation\">📖</a> <a href=\"#maintenance-aignas\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"https://github.com/jackloughran\"><img src=\"https://avatars.githubusercontent.com/u/30052269?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Jack</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=jackloughran\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=jackloughran\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://twitter.com/JSON_C11\"><img src=\"https://avatars.githubusercontent.com/u/5185660?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Jason Cooke</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Jason-Cooke\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/jenting\"><img src=\"https://avatars.githubusercontent.com/u/49380831?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>JenTing Hsiao</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=jenting\" title=\"Code\">💻</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/joelpet\"><img src=\"https://avatars.githubusercontent.com/u/114321?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Joel Pettersson</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=joelpet\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/JojiiOfficial\"><img src=\"https://avatars.githubusercontent.com/u/15957865?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>JojiiOfficial</b></sub></a><br /><a href=\"#maintenance-JojiiOfficial\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"https://github.com/metiis\"><img src=\"https://avatars.githubusercontent.com/u/31927016?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Julia</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=metiis\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/juliangaal\"><img src=\"https://avatars.githubusercontent.com/u/22290570?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Julian Gaal</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=juliangaal\" title=\"Documentation\">📖</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=juliangaal\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/justin-gerhardt\"><img src=\"https://avatars.githubusercontent.com/u/6844979?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Justin Gerhardt</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=justin-gerhardt\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"http://www.katriel.co.uk/\"><img src=\"https://avatars.githubusercontent.com/u/315959?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Katriel Cohn-Gordon</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=katrielalex\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/Gorzen\"><img src=\"https://avatars.githubusercontent.com/u/28461464?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Lucien Iseli</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Gorzen\" title=\"Documentation\">📖</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"http://odois.org/\"><img src=\"https://avatars.githubusercontent.com/u/6931166?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Luiz Bettoni</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=lulis\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/mh84\"><img src=\"https://avatars.githubusercontent.com/u/17948500?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>MH</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=mh84\" title=\"Code\">💻</a> <a href=\"#infra-mh84\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n    <td align=\"center\"><a href=\"https://github.com/Mange\"><img src=\"https://avatars.githubusercontent.com/u/1599?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Magnus Bergmark</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Mange\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/marcelbuesing\"><img src=\"https://avatars.githubusercontent.com/u/5637837?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Marcel</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=marcelbuesing\" title=\"Code\">💻</a> <a href=\"#maintenance-marcelbuesing\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"https://github.com/marijnvanderhorst\"><img src=\"https://avatars.githubusercontent.com/u/7057618?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Marijn van der Horst</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=marijnvanderhorst\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/maringuu\"><img src=\"https://avatars.githubusercontent.com/u/60553448?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Marten Ringwelski</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=maringuu\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"http://mdb.io/\"><img src=\"https://avatars.githubusercontent.com/u/216331?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Matt Bailey</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=mattbailey\" title=\"Documentation\">📖</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://michaelrussell.ninja/\"><img src=\"https://avatars.githubusercontent.com/u/4550136?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Michael Russell</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Crazybus\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/Mitschmaster\"><img src=\"https://avatars.githubusercontent.com/u/39187239?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Mitschmaster</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Mitschmaster\" title=\"Code\">💻</a> <a href=\"#infra-Mitschmaster\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n    <td align=\"center\"><a href=\"https://github.com/nickcorona\"><img src=\"https://avatars.githubusercontent.com/u/7490453?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Nick Corona</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=nickcorona\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://kaiser.me/\"><img src=\"https://avatars.githubusercontent.com/u/238631?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Nico Kaiser</b></sub></a><br /><a href=\"#infra-nicokaiser\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n    <td align=\"center\"><a href=\"http://www.patrikhermansson.se/\"><img src=\"https://avatars.githubusercontent.com/u/3775861?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Patrik Hermansson</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=bphermansson\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/pstruschka\"><img src=\"https://avatars.githubusercontent.com/u/10444945?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Peter Son Struschka</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=pstruschka\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://philippmoers.de/\"><img src=\"https://avatars.githubusercontent.com/u/6862899?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Philipp Moers</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=sflip\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=sflip\" title=\"Documentation\">📖</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/pfrenssen\"><img src=\"https://avatars.githubusercontent.com/u/442924?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Pieter Frenssen</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=pfrenssen\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/Plecra\"><img src=\"https://avatars.githubusercontent.com/u/60934058?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Plecra</b></sub></a><br /><a href=\"#maintenance-Plecra\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"https://pontus-persson.se/\"><img src=\"https://avatars.githubusercontent.com/u/720546?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Pontus Persson</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=PontusPersson\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://qaisjp.com/\"><img src=\"https://avatars.githubusercontent.com/u/923242?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Qais Patankar</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=qaisjp\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/Rik-de-Kort\"><img src=\"https://avatars.githubusercontent.com/u/32839123?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Rik-de-Kort</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Rik-de-Kort\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/robinvd\"><img src=\"https://avatars.githubusercontent.com/u/22073483?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Robin</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=robinvd\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=robinvd\" title=\"Documentation\">📖</a> <a href=\"#infra-robinvd\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a> <a href=\"#maintenance-robinvd\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"https://github.com/RlndVt\"><img src=\"https://avatars.githubusercontent.com/u/1658570?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Roland Vet</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=RlndVt\" title=\"Documentation\">📖</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/Yarn\"><img src=\"https://avatars.githubusercontent.com/u/908816?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Ryan</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Yarn\" title=\"Code\">💻</a> <a href=\"#infra-Yarn\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n    <td align=\"center\"><a href=\"https://github.com/Jalle19\"><img src=\"https://avatars.githubusercontent.com/u/1106133?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Sam Stenvall</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=Jalle19\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://sk22.ml/\"><img src=\"https://avatars.githubusercontent.com/u/6217438?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Samuel Kaiser</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=sk22\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"http://smgt.me/\"><img src=\"https://avatars.githubusercontent.com/u/2408?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Simon Gate</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=smgt\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/SimonPersson\"><img src=\"https://avatars.githubusercontent.com/u/606973?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Simon Persson</b></sub></a><br /><a href=\"#maintenance-SimonPersson\" title=\"Maintenance\">🚧</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=SimonPersson\" title=\"Documentation\">📖</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=SimonPersson\" title=\"Code\">💻</a> <a href=\"#infra-SimonPersson\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n    <td align=\"center\"><a href=\"https://github.com/SirWindfield\"><img src=\"https://avatars.githubusercontent.com/u/5113257?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>SirWindfield</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=SirWindfield\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=SirWindfield\" title=\"Documentation\">📖</a> <a href=\"#infra-SirWindfield\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a> <a href=\"#maintenance-SirWindfield\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"http://metafly.info/\"><img src=\"https://avatars.githubusercontent.com/u/961256?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Stefan Sydow</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=stsydow\" title=\"Code\">💻</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/vringar\"><img src=\"https://avatars.githubusercontent.com/u/13276717?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Stefan Zabka</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=vringar\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"http://stuarth.github.io/\"><img src=\"https://avatars.githubusercontent.com/u/7055?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Stuart Hinson</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=stuarth\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/ghishadow\"><img src=\"https://avatars.githubusercontent.com/u/9583775?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Suraj Ghimire</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=ghishadow\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/timotk\"><img src=\"https://avatars.githubusercontent.com/u/6358247?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Timo</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=timotk\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/TimotheeGerber\"><img src=\"https://avatars.githubusercontent.com/u/37541513?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Timothée Gerber</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=TimotheeGerber\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/TobiMichael96\"><img src=\"https://avatars.githubusercontent.com/u/43846093?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Tobias Michael Effner</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=TobiMichael96\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/valir\"><img src=\"https://avatars.githubusercontent.com/u/4358494?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Valentin Rusu</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=valir\" title=\"Code\">💻</a> <a href=\"https://github.com/Spotifyd/spotifyd/commits?author=valir\" title=\"Documentation\">📖</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/vickychenglau\"><img src=\"https://avatars.githubusercontent.com/u/22065437?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Vicky C Lau</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=vickychenglau\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/wvangeit\"><img src=\"https://avatars.githubusercontent.com/u/3098670?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Werner Van Geit</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=wvangeit\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/wdehoog\"><img src=\"https://avatars.githubusercontent.com/u/3353303?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Willem-Jan de Hoog</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=wdehoog\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/jb55\"><img src=\"https://avatars.githubusercontent.com/u/45598?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>William Casarin</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=jb55\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/johnalanwoods\"><img src=\"https://avatars.githubusercontent.com/u/5158898?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Woodstock</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=johnalanwoods\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/aksel\"><img src=\"https://avatars.githubusercontent.com/u/6985716?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>aksel</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=aksel\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://ashleytqy.github.io/\"><img src=\"https://avatars.githubusercontent.com/u/11889765?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>ashley teoh</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=ashleytqy\" title=\"Documentation\">📖</a></td>\n  </tr>\n  <tr>\n    <td align=\"center\"><a href=\"https://github.com/backspac\"><img src=\"https://avatars.githubusercontent.com/u/8981640?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>backspac</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=backspac\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/dcoppa\"><img src=\"https://avatars.githubusercontent.com/u/1073526?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>dcoppa</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=dcoppa\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/dimlev\"><img src=\"https://avatars.githubusercontent.com/u/1188269?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>dimlev</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=dimlev\" title=\"Documentation\">📖</a></td>\n    <td align=\"center\"><a href=\"https://github.com/MarinPostma\"><img src=\"https://avatars.githubusercontent.com/u/28804882?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>marin</b></sub></a><br /><a href=\"#maintenance-MarinPostma\" title=\"Maintenance\">🚧</a></td>\n    <td align=\"center\"><a href=\"https://tommady.com/\"><img src=\"https://avatars.githubusercontent.com/u/11532828?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>tommady</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=tommady\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/zv0n\"><img src=\"https://avatars.githubusercontent.com/u/17143863?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>zv0n</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=zv0n\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/sckova\"><img src=\"https://avatars.githubusercontent.com/u/48322391?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>sckova</b></sub></a><br /><a href=\"https://github.com/Spotifyd/spotifyd/commits?author=sckova\" title=\"Code\">💻</a></td>\n  </tr>\n</table>\n\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nauthors = [\"Simon Persson <simon@flaskpost.org>\", \"Sven Lechner <sven.lechner@rwth-aachen.de>\", \"eladyn <eladyn@protonmail.com>\"]\nedition = \"2024\"\nname = \"spotifyd\"\ndescription = \"A Spotify daemon\"\nrepository = \"https://github.com/Spotifyd/spotifyd\"\nlicense = \"GPL-3.0-only\"\nversion = \"0.4.2\"\nresolver = \"2\"\nrust-version = \"1.88\"\n\n[dependencies]\nalsa = { version = \"0.10.0\", optional = true }\nchrono = \"0.4\"\ndbus = { version = \"0.9\", optional = true }\ndbus-tokio = { version = \"0.7.3\", optional = true }\ndbus-crossroads = { version = \"0.5.0\", optional = true }\nfern = { version = \"0.7.0\", features = [\"syslog-7\", \"colored\"] }\nfutures = \"0.3.15\"\ngethostname = \"1.0.0\"\nhex = \"0.4\"\nlibc = \"0.2.82\"\nlog = \"0.4.6\"\nserde = { version = \"1.0.115\", features = [\"derive\"] }\nsha-1 = \"0.10\"\ntokio = {version = \"1.44.2\", features = [\"signal\", \"rt-multi-thread\", \"process\", \"io-std\"] }\ntokio-stream = \"0.1.7\"\nurl = \"2.2.2\"\nlibrespot-audio = { version = \"0.8.0\", default-features = false }\nlibrespot-playback = { version = \"0.8.0\", default-features = false }\nlibrespot-core = \"0.8.0\"\nlibrespot-discovery = \"0.8.0\"\nlibrespot-connect = \"0.8.0\"\nlibrespot-metadata = \"0.8.0\"\nlibrespot-protocol = \"0.8.0\"\nlibrespot-oauth = \"0.8.0\"\ntoml = \"0.9.8\"\ncolor-eyre = \"0.6\"\ndirectories = \"6.0.0\"\nthiserror = \"2.0\"\ntime = { version = \"0.3.47\", default-features = false, features = [\"formatting\"] }\nclap = { version = \"4.5.23\", features = [\"derive\"] }\nserde_ignored = \"0.1.10\"\n\n[target.'cfg(unix)'.dependencies]\ndaemonize = \"0.5\"\nsyslog = \"7\"\n\n[target.'cfg(target_os = \"macos\")'.dependencies]\nwhoami = \"1\"\n\n[target.'cfg(target_os = \"openbsd\")'.dependencies]\npledge = \"0.4.2\"\n\n[target.'cfg(not(any(target_arch = \"aarch64\", target_arch = \"x86_64\")))'.dependencies]\naws-lc-rs = { version = \"1.12.6\", features = [\"bindgen\"] }\n\n[dev-dependencies]\nenv_logger = \"0.11\"\n\n[features]\nalsa_backend = [\"librespot-playback/alsa-backend\", \"dep:alsa\"]\ndbus_mpris = [\"dep:dbus\", \"dep:dbus-tokio\", \"dep:dbus-crossroads\"]\ndefault = [\"alsa_backend\", \"pulseaudio_backend\", \"dbus_mpris\"]\nportaudio_backend = [\"librespot-playback/portaudio-backend\"]\npulseaudio_backend = [\"librespot-playback/pulseaudio-backend\"]\nrodio_backend = [\"librespot-playback/rodio-backend\"]\nrodiojack_backend = [\"librespot-playback/rodiojack-backend\"]\n\n[package.metadata.deb]\ndepends = \"$auto\"\nfeatures = [\"pulseaudio_backend\", \"dbus_mpris\"]\nassets = [\n    [\"target/release/spotifyd\", \"usr/bin/\", \"755\"],\n    [\"README.md\", \"usr/share/doc/spotifyd/README\", \"644\"],\n    [\"contrib/spotifyd.service\", \"etc/systemd/user/\", \"644\"],\n]\n\n[package.metadata.generate-rpm]\nassets = [\n    { source = \"target/release/spotifyd\", dest = \"/usr/bin/spotifyd\", mode = \"755\" },\n    { source = \"README.md\", dest = \"/usr/share/doc/spotifyd/README\", mode = \"644\" },\n    { source = \"contrib/spotifyd.service\", dest = \"/etc/systemd/user/spotifyd.service\", mode = \"644\" },\n]\n\n[profile.release]\nlto = true\n\n##### uncomment to test the newest librespot git version\n# [patch.crates-io]\n# librespot-audio = { git = \"https://github.com/librespot-org/librespot\" }\n# librespot-playback = {  git = \"https://github.com/librespot-org/librespot\" }\n# librespot-core = { git = \"https://github.com/librespot-org/librespot\" }\n# librespot-discovery = { git = \"https://github.com/librespot-org/librespot\" }\n# librespot-connect = { git = \"https://github.com/librespot-org/librespot\" }\n# librespot-metadata = { git = \"https://github.com/librespot-org/librespot\" }\n# librespot-protocol = { git = \"https://github.com/librespot-org/librespot\" }\n# librespot-oauth = { git = \"https://github.com/librespot-org/librespot\" }\n"
  },
  {
    "path": "Cross.toml",
    "content": "[build]\npre-build = [\n  \"dpkg --add-architecture $CROSS_DEB_ARCH\",\n  \"apt-get update\",\n  # bindgen requirements\n  \"apt-get install -y libclang-dev cmake\",\n  # alsa_backend,rodio_backend and base requirements\n  \"apt-get install -y libasound2-dev:$CROSS_DEB_ARCH libssl-dev:$CROSS_DEB_ARCH\",\n  # dbus_mpris\n  \"apt-get install -y libdbus-1-dev:$CROSS_DEB_ARCH\",\n  # pulseaudio_backend\n  \"apt-get install -y libpulse-dev:$CROSS_DEB_ARCH\",\n  # portaudio_backend\n  \"apt-get install -y portaudio19-dev:$CROSS_DEB_ARCH\",\n]\n\n[target.armv7-unknown-linux-gnueabihf]\nimage = \":edge\" # needed, since dbus and pulse dependencies on older ubuntu versions are messy\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Spotifyd <!-- omit in toc -->\n\n[![Matrix][matrix-badge]](https://matrix.to/#/#spotifyd:matrix.org)\n[![GitHub Workflow Status][cd-badge]][github-actions]\n[![Github Actions - CI][ci-badge]][github-actions]\n\n> An open source Spotify client running as a UNIX daemon.\n\n[Project Website](https://spotifyd.rs)\n\nSpotifyd 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.\n\n> __Note:__ Spotifyd requires a Spotify Premium account.\n\n__To read about how to install and configure Spotifyd, take a look at our [wiki][wiki]!__\n\n## Contributing\n\nWe 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.\n\n## Credits\n\nThis 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).\n\n<!-- This section contains all links used within the document. This prevents cluttering and makes reading the raw markdown a lot easier -->\n[github-actions]: https://github.com/Spotifyd/spotifyd/actions\n[good-first-issues]: https://github.com/Spotifyd/spotifyd/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22\n[matrix-badge]: https://img.shields.io/matrix/spotifyd:matrix.org?logo=matrix&server_fqdn=matrix.org\n[cd-badge]: https://img.shields.io/github/actions/workflow/status/Spotifyd/spotifyd/cd.yml?label=continuous%20deployment&logo=github\n[ci-badge]: https://img.shields.io/github/actions/workflow/status/Spotifyd/spotifyd/ci.yml?label=continuous%20integration&logo=github\n[wiki]: https://spotifyd.github.io/spotifyd/\n"
  },
  {
    "path": "contrib/spotifyd.conf",
    "content": "[global]\n\n#---------#\n# GENERAL #\n#---------#\n\n# The name that gets displayed under the connect tab on\n# official clients.\n#device_name = \"device_name_in_spotify_connect\"\n\n# The displayed device type in Spotify clients.\n# Can be unknown, computer, tablet, smartphone, speaker, t_v,\n# a_v_r (Audio/Video Receiver), s_t_b (Set-Top Box), and audio_dongle.\n#device_type = \"speaker\"\n\n# The directory used to store credentials and audio cache.\n# Default: infers a sensible cache directory (e.g. on Linux: $XDG_CACHE_HOME)\n#\n# Note: The file path does not get expanded. Environment variables and\n# shell placeholders like $HOME or ~ don't work!\n#cache_path = \"/full/path/to/cache/directory\"\n\n# If set to true, audio data does NOT get cached.\n# In this case, the cache is only used for credentials.\n#no_audio_cache = true\n\n# The maximal size of the cache directory in bytes\n# The example value corresponds to ~ 1GB\n#max_cache_size = 1000000000\n\n# If set to true, `spotifyd` tries to bind to dbus (default is the session bus)\n# and expose MPRIS controls. When running headless, without the session bus,\n# you should set this to false, to avoid errors. If you still want to use MPRIS,\n# have a look at the `dbus_type` option.\n#use_mpris = true\n\n# The bus to bind to with the MPRIS interface.\n# Possible values: \"session\", \"system\"\n# The system bus can be used if no graphical session is available\n# (e.g. on headless systems) but you still want to be able to use MPRIS.\n# NOTE: You might need to add appropriate policies to allow spotifyd to\n# own the name.\n#dbus_type = \"session\"\n\n#-----------#\n# DISCOVERY #\n#-----------#\n\n# If set to true, this disables zeroconf discovery.\n# This can be useful, if one prefers to run a single-user instance.\n#disable_discovery = false\n\n# The port at which `spotifyd` is going to offer its service over the network (TCP).\n# If not set, a random port > 1024 is used. For the service to be discoverable on the\n# local network via mDNS, both the mDNS port (5353 UDP) and the random or fixed\n# zeroconf port need to be allowed through any active firewall.\n#zeroconf_port = 1234\n\n#-------#\n# AUDIO #\n#-------#\n\n# The audio backend used to play music. To get\n# a list of possible backends, run `spotifyd --help`.\n#backend = \"alsa\" # use portaudio for macOS [homebrew]\n\n# The alsa audio device to stream audio. To get a\n# list of valid devices, run `aplay -L`,\n#device = \"default\"  # omit for macOS\n\n# The PCM sample format to use. Possible values \n# are F32, S32, S24, S24_3, S16. \n# Change this value if you encounter errors like\n# \"Alsa error PCM open ALSA function 'snd_pcm_hw_params_set_format' failed with error 'EINVAL: Invalid argument'\"\n#audio_format = \"S16\"\n\n# The volume controller. Each one behaves different to\n# volume increases. For possible values, run\n# `spotifyd --help`.\n#volume_controller = \"softvol\"  # use softvol for macOS\n\n# ! Only relevant for ALSA !\n# The alsa control device. By default this is the same\n# name as the `device` field.\n#control = \"default\"\n\n# ! Only relevant for ALSA !\n# The alsa mixer used by `spotifyd`.\n#mixer = \"PCM\"  # omit for macOS\n\n# The audio bitrate. 96, 160 or 320 kbit/s\n#bitrate = 160\n\n# Volume on startup between 0 and 100\n#initial_volume = 90\n\n# If set to true, enables volume normalisation between songs.\n#volume_normalisation = true\n\n# The normalisation pregain that is applied for each song.\n#normalisation_pregain = -10\n\n#-------ä\n# OTHER #\n#-------#\n\n# After the music playback has ended, start playing similar songs based on the previous tracks.\n# By default, `spotifyd` infers this setting from the user settings.\n#autoplay = true\n\n# A command that gets executed in your shell after each song changes.\n#on_song_change_hook = \"echo \\\"hook executed on $PLAYER_EVENT\\\"\"\n\n# The proxy `spotifyd` will use to connect to spotify.\n#proxy = \"http://proxy.example.org:8080\"\n"
  },
  {
    "path": "contrib/spotifyd.service",
    "content": "[Unit]\nDescription=A spotify playing daemon\nDocumentation=https://github.com/Spotifyd/spotifyd\nWants=sound.target\nAfter=sound.target\nWants=network-online.target\nAfter=network-online.target\n\n[Service]\nExecStart=/usr/bin/spotifyd --no-daemon\nRestart=always\nRestartSec=12\n\n[Install]\nWantedBy=default.target\n"
  },
  {
    "path": "docs/.gitignore",
    "content": "book"
  },
  {
    "path": "docs/book.toml",
    "content": "[book]\nauthors = [\"@Spotifyd/maintainers and contributors\"]\nlanguage = \"en\"\nmultilingual = false\nsrc = \"src\"\ntitle = \"Spotifyd\"\n"
  },
  {
    "path": "docs/src/Introduction.md",
    "content": "# Introduction\n\nThis is the documentation of [spotifyd][spotifyd], which covers the installation and setup process as well as some advanced topics.\n\n## Getting Help\n\nIf you're stuck in the setup process or have a question, please join the [community matrix server][matrix]. We're always willing to help!\n\n[spotifyd]: https://github.com/Spotifyd/spotifyd\n[matrix]: https://matrix.to/#/#spotifyd:matrix.org\n"
  },
  {
    "path": "docs/src/SUMMARY.md",
    "content": "# Spotifyd\n\n[Introduction](./Introduction.md)\n\n- [Installation](./installation/README.md)\n  - [Running as a service](./installation/service.md)\n  - [Building from source](./installation/source.md)\n  - [Cross-Compilation](./installation/cross-compilation.md)\n- [Configuration](./configuration/README.md)\n  - [Authentication](./configuration/auth.md)\n  - [Audio](./configuration/audio.md)\n  - [Other settings](./configuration/other.md)\n- [Advanced Setup](./advanced/README.md)\n  - [Running as systemd service](./advanced/systemd.md)\n  - [Running as launchd service](./advanced/launchd.md)\n  - [Using D-Bus to control `spotifyd`](./advanced/dbus.md)\n  - [MPRIS on headless systems](./advanced/mpris.md)\n  - [Extending spotifyd with hooks](./advanced/hooks.md)\n- [Troubleshooting](./troubleshooting.md)\n"
  },
  {
    "path": "docs/src/advanced/README.md",
    "content": "# Advanced Setup\n\nIn 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.\n"
  },
  {
    "path": "docs/src/advanced/dbus.md",
    "content": "# Using D-Bus to control spotifyd\n\nIf 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.\n\nMost 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.\n\n## Available Interfaces\n\nDirectly 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`.\n\nAs 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`.\n\n### Spotifyd Controls\n\nThe `rs.spotifyd.Controls` interface exposes a few useful controls that are available even if we're not the active playback device.\n\n- Method `TransferPlayback`: transfers Spotify playback to `spotifyd`\n- Method `VolumeUp`: increases player volume\n- Method `VolumeDown`: decreases player volume\n\nExamples:\n```bash\ndest=rs.spotifyd.instance$(pidof spotifyd)\n# increase volume\ndbus-send --print-reply --dest=$dest /rs/spotifyd/Controls rs.spotifyd.Controls.VolumeUp\n# become the active playback device\ndbus-send --print-reply --dest=$dest /rs/spotifyd/Controls rs.spotifyd.Controls.TransferPlayback\n```\n\n### MPRIS\n\nThe `org.mpris.MediaPlayer2` and `org.mpris.MediaPlayer2.Player` interfaces from the [MPRIS specification](https://specifications.freedesktop.org/mpris-spec/latest/) are implemented.\n\nExample usage:\n```bash\ndest=org.mpris.MediaPlayer2.spotifyd.instance$(pidof spotifyd)\n# Start playback of some Spotify URI\ndbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.OpenUri string:spotify:track:4PTG3Z6ehGkBFwjybzWkR8\n# Get metadata of the currently playing track\ndbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:org.mpris.MediaPlayer2.Player string:Metadata\n```\n\n## Examples\n\nStarting Playback without Client:\n```bash\n#!/bin/bash\n\n# optionally, we can start `spotifyd` here\nif ! pidof -q spotifyd\nthen\n  spotifyd --use-mpris\nfi\n\ndest=rs.spotifyd.instance$(pidof spotifyd)\n\nwait_for_name() {\n  dst=$1\n  counter=0\n\n  # check if controls are available\n  until [ $counter -gt 10 ] || (dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ListNames | grep -q \"$dest\")\n  do\n    sleep 0.3\n    ((counter++))\n  done\n\n  if [ $counter -gt 10 ]\n  then\n    echo \"waiting for spotifyd timed out\" >&1\n    exit 1\n  fi\n}\n\ncontrols_name=rs.spotifyd.instance$(pidof spotifyd)\nwait_for_name $controls_name\necho \"Transferring Playback\"\ndbus-send --print-reply --dest=$controls_name /rs/spotifyd/Controls rs.spotifyd.Controls.TransferPlayback\n\n# if URI is specified, start the playback there\nif [ -n \"$1\" ]\nthen\n  uri=\"$1\"\n  mpris_name=org.mpris.MediaPlayer2.spotifyd.instance$(pidof spotifyd)\n  wait_for_name $mpris_name\n  echo \"Starting Playback of $uri\"\n  dbus-send --print-reply --dest=$mpris_name /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.OpenUri \"string:$uri\"\nelse\n  echo \"Hint: specify an argument to start playback of a specific Spotify URI\"\nfi\n```\n\nSleep Timer:\n```bash\n#!/bin/bash\n\nusage() {\n  echo \"Usage: $0 <timeout>\" >&1\n  exit 1\n}\n\n[ -n \"$1\" ] || usage\n\necho \"Sleeping for $1 seconds\"\nsleep $1\n\ndest=org.mpris.MediaPlayer2.spotifyd.instance$(pidof spotifyd)\ndbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ListNames | grep -q \"$dest\"\n\nif [ \"$?\" = \"0\" ]\nthen\n  dbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Stop\n  # alternatively just pause:\n  # dbus-send --print-reply --dest=$dest /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Pause\nelse\n  echo \"No active spotifyd playback.\"\nfi\n```\n"
  },
  {
    "path": "docs/src/advanced/hooks.md",
    "content": "# User supplied Scripts\n\nIf 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.\n\nTo point `spotifyd` to such a script, use the `--onevent /path/to/script` cli arg / `on_song_change_hook = \"/path/to/script\"` configuration value.\n\nIn 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.\n\nThe 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!\n\n## Dunst Notifications (Using Spotify API)\n\nThis 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.\n\n### Dependencies\n\n* curl (Request to APIs)\n* xargs (Argument passing)\n* cut\n* jq (https://stedolan.github.io/jq) (for JSON parsing)\n\n### How to use\n\n* Create a file containing the script below:\n\n    ```bash\n    user_id=YOUR_USER_ID # generated on https://developer.spotify.com/dashboard/applications\n    secret_id=YOUR_SECRET_ID\n\n    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)\n    RESULT=$?\n\n    if [ \"$PLAYER_EVENT\" = \"start\" ];\n    then\n        if [ $RESULT -eq 0 ]; then\n            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\n        else\n            echo \"Cannot get token.\"\n        fi\n    elif [ \"$PLAYER_EVENT\" = \"change\" ];\n    then\n        if [ $RESULT -eq 0 ]; then\n            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\n        else\n            echo \"Cannot get token.\"\n        fi\n    elif [ \"$PLAYER_EVENT\" = \"stop\" ];\n    then\n        if [ $RESULT -eq 0 ]; then\n            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\n        else\n            echo \"Cannot get token.\"\n        fi\n    else\n        echo \"Unknown event.\"\n    fi\n    ```\n\n* Make this script executable (`chmod +x notification_script.sh`)\n* Add the line `onevent = \"bash /home/YOU_USER/bin/spotifyNotifications.sh\"` to your `spotifyd.conf`\n"
  },
  {
    "path": "docs/src/advanced/launchd.md",
    "content": "# Running as launchd service\n\nOn macOS, the system wide and per-user daemon/agent manager is known as `launchd`. Interfacing with `launchd` is performed through `launchctl`.\n\nIn order to use `spotifyd` as a service on macOS one must specify a `.plist` that represents the service, and place it in `/Library/LaunchDaemons`.\n\nHere is a .plist which works with macOS Catalina 10.15.3:\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n    <dict>\n\t\t<key>Label</key>\n\t\t<string>rustlang.spotifyd</string>\n\t\t<key>ProgramArguments</key>\n\t\t<array>\n\t\t\t<string>/usr/local/bin/spotifyd</string>\n\t\t\t<string>--config-path=/users/YourUserName/.config/spotifyd/spotifyd.conf</string>\n\t\t\t<string>--no-daemon</string>\n\t\t</array>\n\t\t<key>UserName</key>\n\t\t<string>YourUserName</string>\n\t\t<key>KeepAlive</key>\n\t\t<true/>\n\t\t<key>ThrottleInterval</key>\n\t\t<integer>30</integer>\n\t</dict>\n</plist>\n```\n\nOnce present in the `/Library/LaunchDaemons` directory, the .plist must be loaded and started with the following commands.\n\n`sudo launchctl load -w /Library/LaunchDaemons/rustlang.spotifyd.plist`\n\n\n`sudo launchctl start /Library/LaunchDaemons/rustlang.spotifyd.plist`\n\nOne may also unload/stop the service in a similar fashion replacing load/start with unload/stop.\n\nNote:\n\n* You should update \"YourUserName\" with your actual username for macOS (or remove \"UserName\" to run as root.\n\n* The string, `<string>--no-daemon</string>` 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.\n\n* 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.\n"
  },
  {
    "path": "docs/src/advanced/mpris.md",
    "content": "# MPRIS on headless systems\n\nD-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.\n\nIn this case, you basically have two options:\n\n## Option 1: Launch with `dbus-launch`\n\nBy creating a wrapper script and using `dbus-launch`, `spotifyd` can be run with its own bus. This could look like the following\n\n`./spotify_wrapper.sh`:\n```bash\n#!/bin/bash\n\necho \"$DBUS_SESSION_BUS_ADDRESS\" > /tmp/spotifyd_bus\necho \"To use spotifyd's session bus, run 'export DBUS_SESSION_BUS_ADDRESS=$(cat /tmp/spotifyd_bus)'\"\nspotifyd --no-daemon --use-mpris\n```\n\nThen, execute this script using `dbus-launch ./spotify_wrapper.sh` and follow the instructions in the output.\n\n## Option 2: Using the system bus\n\nInstead of creating a new session bus, we can instead make use of the always existing system bus.\nTo instruct `spotifyd` to use the system instead of the session bus, set the `--dbus-type system` cli flag / `dbus_type = \"system\"` config value.\n\nBy 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):\n\n`/usr/share/dbus-1/system.d/spotifyd.conf`:\n```xml\n<!DOCTYPE busconfig PUBLIC\n          \"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN\"\n          \"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd\">\n<busconfig>\n  <!-- Only this user can own the spotifyd interfaces -->\n  <policy user=\"your user\">\n    <allow own_prefix=\"rs.spotifyd\"/>\n    <allow own_prefix=\"org.mpris.MediaPlayer2.spotifyd\"/>\n  </policy>\n\n  <!-- Allow this user, to invoke methods on these two interfaces -->\n  <policy user=\"your user\">\n    <allow send_destination_prefix=\"rs.spotifyd\"/>\n    <allow send_destination_prefix=\"org.mpris.MediaPlayer2.spotifyd\"/>\n  </policy>\n</busconfig>\n```\n\nMake sure to reload the D-Bus configuration with `systemctl reload dbus`.\n"
  },
  {
    "path": "docs/src/advanced/systemd.md",
    "content": "# Running as systemd service\n\n## As as a user service\n\nA `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:\n\n```bash\n/etc/systemd/user/\n~/.config/systemd/user/\n```\n\nPackagers 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`.\n\nControl 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.\n\n```bash\nsystemctl --user enable spotifyd.service --now\n```\n\n## As a system wide service\n\n<div class=\"warning\">\n\nWhen 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.\n\nAdditionally, `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).\n\n</div>\n\nA `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:\n\n```bash\n/etc/systemd/system/\n```\n\nControl of the daemon is handed over to systemd. The following example commands will start the service and keep it running across reboots.\n\n```bash\nsystemctl daemon-reload\nsystemctl enable spotifyd.service --now\n```\n"
  },
  {
    "path": "docs/src/configuration/README.md",
    "content": "# Configuration\n\n`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.\n\nAll 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.\n\n## Config File\n\n`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 <path-to-your-config>`.\n\nYou can start with the following documented config as an example and read through the subpages of this section:\n```toml\n{{#include ../../../contrib/spotifyd.conf}}\n```\n"
  },
  {
    "path": "docs/src/configuration/audio.md",
    "content": "# Audio Configuration\n\nOn 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.\n\n## Backend\n\n> `-b/--backend` or `backend` in the config file.\n\nThere are different audio backends available to choose from. See `spotifyd --help` to get the available names.\n\n## Device selection\n\n> `--device` or `device` in the config file.\n\nInstead 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.\n\n- For ALSA, you can use `aplay -L` to get a list of possible devices.\n- For PulseAudio, run `pactl list short sinks` to get a list of possible names.\n\n## Bitrate\n\n> `-B/--bitrate` or `bitrate` in the config file.\n\nTo reduce bandwidth usage or increase quality, you can play with the bitrate.\n\n## Volume Controller\n\n> `--volume-controller` or `volume_controller` in the config file.\n\nIn most cases, leaving this at the default (`softvol`) should be fine.\n\nIf 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.\n\nIf you want to prevent the user to be able to adjust the volume, set this instead to `none`.\n\n## Other\n\nFor more interesting but less relevant audio options, have a look at `spotifyd --help` or [the example config](./).\n"
  },
  {
    "path": "docs/src/configuration/auth.md",
    "content": "# Authentication\n\nThere are two different ways of authentication supported.\n\n## Discovery on LAN\n\nBy 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.\n\nFor this to work, you need to make sure that your firewall isn't blocking the discovery. In particular, `spotifyd` uses two ports:\n\n- `5353 UDP`: MDNS service advertisement\n- 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.\n\nIf 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.\n\n> __Note:__ By default, the last active session will be remembered and reconnected once the service is restarted.\n\n## Manual Login (via OAuth)\n\nIf 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.\n\n> __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 `<cache_path>/oauth/credentials.json`.\n\nBefore 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.\n\nNow, you're ready to run `spotifyd authenticate` (for available options, see `spotifyd auth --help`).\nThis 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.\n\nIf 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.\n\nNow, when running `spotifyd --no-daemon`, you should see that `spotifyd` automatically connects to your account.\n\n```\nLoading config from \"...\"\n[...]\nLogin via OAuth as user <your username>.\n[...]\nAuthenticated as '<your username>' !\n```\n\n> __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.\n"
  },
  {
    "path": "docs/src/configuration/other.md",
    "content": "# Other settings\n\n## Appearance\n\nYou can customize, how your device is displayed in clients with `--device-name` / `device_name` and `--device-type` / `device_type` options.\n\n## Caching\n\nYou can enable audio data caching by setting a `--cache-path` / `cache_path` and limit its size with `--max-cache-size` / `max_cache_size`.\n\n## MPRIS\n\nOn 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`.\n"
  },
  {
    "path": "docs/src/installation/README.md",
    "content": "# Installation\n\nGetting `spotifyd` on your system should be as easy as downloading a binary in most cases.\nIf you'd like to learn how to compile `spotifyd` yourself, head over to [building from source](./source.md).\n\n## Linux\n\nSome linux distributions include `spotifyd` in their official repositories. Have a look at [Repology](https://repology.org/project/spotifyd/versions)\nfor a list of the distributions that currently ship an up-to-date version of `spotifyd`.\n\nIf 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.\n\n## macOS\n\nIf you're a homebrew user, installing `spotifyd` is as easy as running\n\n```console\nbrew install spotifyd\n```\n\n## FreeBSD\n\nOn FreeBSD, a package is available and can be installed with `pkg install spotifyd`.\n\n## OpenBSD\n\nOn OpenBSD, a package is available and can be installed with `pkg_add spotifyd`.\n\n## Installing from releases\n\nIf none of the above methods work for you, you can also use our provided binaries.\n\nFirst, you need to find a suitable binary for your platform. The provided binaries differ in the available features\nand the platform architecture that they were built for. You can find the latest binaries [here](https://github.com/Spotifyd/spotifyd/releases).\n\n**Feature Sets:**\n\n- `full`: **all audio backends** and **MPRIS** support\n- `default`: **some audio backends** (depending on your platform: PulseAudio, PortAudio, ALSA) and **MPRIS** support\n- `slim`: **one audio backend** (depending on your platform) and **no MPRIS** support (good for headless systems)\n\nIf you're unsure which version to choose, just go for `default` on desktop systems and `slim` on headless systems.\n\n**Architecture:**\n\nIf you're on Linux, check your platform architecture with `uname -m`:\n\n- `x86_64`: Download one of the `spotifyd-linux-x86_64-{full,default,slim}.tar.gz` packages.\n- `armhf`, `armv7`: Download one of the `spotifyd-linux-armv7-{full,default,slim}.tar.gz` packages.\n- `aarch64`: Download one of the `spotifyd-linux-aarch64-{full,default,slim}.tar.gz`\n- `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.\n\nIf you're on macOS, download one of the `spotifyd-macos-{full,default,slim}.tar.gz` packages.\n\nYou 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:\n\n```console\n$ tar xzf spotifyd-*.tar.gz # extract\n$ cd spotifyd-*/\n$ chmod +x spotifyd # make binary executable\n$ # move to correct location, e.g. on Linux:\n$ # for a user-wide installation (make sure that your $PATH includes ~/.local/bin)\n$ mv spotifyd ~/.local/bin/spotifyd\n$ # for a system-wide installation\n$ sudo chown root:root spotifyd\n$ sudo mv spotifyd /usr/local/bin/spotifyd\n```\n\n## Running\n\nNow that you have installed `spotifyd`, you can check if everything was successful by running `spotifyd --version`.\n\nYou 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.\nIf this does not work, you can head over to the [troubleshooting section](../troubleshooting.md) or look at [different methods of authentication](../configuration/auth.md).\n"
  },
  {
    "path": "docs/src/installation/cross-compilation.md",
    "content": "# Cross-Compilation\n\nIf 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.\n\n## Using `cross`\n\nThe 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.\nFollow the instructions in their README to install `cross`.\n\n<div class=\"warning\">\n\nIn 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.\n\n</div>\n\nThen, you should be able to run `cross build --target <your desired 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.\n\nIf this was successful, copy the resulting binary from `target/<your desired target>/{release,debug}/spotifyd` to the `spotifyd` machine and try running it there.\n\nIf `cross` doesn't support your target, you can try the alternative approach using Docker and QEMU below.\n\nIf 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.\n\n## Using Docker and QEMU\n\nWe can also use `docker` to cross compile on every platform and OS that runs `docker` and `qemu`:\n\n1. Setup a docker [custom builder](https://docs.docker.com/build/building/multi-platform/#create-a-custom-builder)\n\n    ```shell\n    docker buildx create \\\n      --name container-builder \\\n      --driver docker-container \\\n      --use --bootstrap\n    ```\n\n    If you are **not** using Docker-Desktop you might have to install [QEMU](https://docs.docker.com/build/building/multi-platform/#install-qemu-manually)\n\n2. Create a docker `docker-compose.yml`\n\n    Here we are building a `arm64` binary, so we set `platform: linux/arm64`\n\n    ```yaml\n    services:\n      build-container:\n        image: rust:1-bookworm\n        platform: linux/arm64\n        command: bash -c \"\n            apt-get update &&\n            apt-get install -y \\\n              libasound2-dev \\\n              libssl-dev \\\n              jq \\\n              pkg-config &&\n            wget -O - https://api.github.com/repos/Spotifyd/spotifyd/tarball/$(\\\n                curl -SsL https://api.github.com/repos/Spotifyd/spotifyd/releases/latest \\\n                  | jq '.tag_name' -r) \\\n              | tar xzv -C /spotifyd --strip-components=1 &&\n            cargo build --release &&\n            cp /spotifyd/target/release/spotifyd /build/\"\n        working_dir: /spotifyd\n        volumes:\n          - ./:/build\n    ```\n\n3. Run `docker compose up`\n\n    This will copy the build `spotifyd` binary in the current directory.\n"
  },
  {
    "path": "docs/src/installation/service.md",
    "content": "# Running as a service\n\nMost people want to have `spotifyd` always running in the background. The preferred method to do this depends on the OS you're using.\n\n## Linux\n\nIf you installed `spotifyd` directly from your distribution, chances are that the installation includes a service definition such that you can run\n\n```console\n$ systemctl --user start spotifyd # start spotifyd using systemd\n$ systemctl --user enable --now spotifyd # start spotifyd and enable starting on login\n```\n\nIf you installed `spotifyd` some other way, head over to [the advanced section](../advanced/systemd.md) for further instructions.\n\n## macOS\n\nIf you installed `spotifyd` using brew, the following commands should do the trick\n\n```console\n$ brew services run spotifyd # start the service once\n$ brew services start spotifyd # start spotifyd and enable starting on boot\n```\n\nIf you installed `spotifyd` without brew, [the advanced section](../advanced/launchd.md) has got you covered.\n\n## FreeBSD\n\nWhen installed via the package manager, the following commands are available:\n\n```console\n$ sudo service spotifyd onestart # start spotifyd once\n$ sudo sysrc spotifyd_enable=YES # enable starting spotifyd on boot\n```\n"
  },
  {
    "path": "docs/src/installation/source.md",
    "content": "# Building from source\n\nThe 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).\n\nYou 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.\n\n> __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.\n\n## Required packages\n\n`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.\n\n| Target Platform | Libraries                                            |\n|-----------------|------------------------------------------------------|\n| Fedora          | alsa-lib-devel make gcc                              |\n| openSUSE        | alsa-devel make gcc                                  |\n| Debian          | libasound2-dev libssl-dev libpulse-dev libdbus-1-dev |\n| Arch            | base-devel alsa-lib libogg libpulse dbus             |\n| macOS           | dbus pkg-config portaudio                            |\n\nIf 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).\n\n## Installing with cargo\n\nTo build and install the latest version of `spotifyd`, you can use the package manager for rust. The base command is the following\n\n```console\ncargo install spotifyd --locked\n```\n\nIf you would rather install from the latest commit on GitHub, download or clone the project, enter the directory and run\n\n```console\ncargo install --path . --locked\n```\n\n> __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.\n\n## Compiling with cargo\n\nTo just build the binary without installing, run\n\n```console\ncargo build --release --locked\n```\n\nThis will build the binary and leave the result at `./target/release/spotifyd`.\n\n## Building a Debian package\n\nYou can use the `cargo-deb` crate in order to build a Debian package from source.\nInstall it by:\n\n```console\ncargo install cargo-deb\n```\n\nThen you can build and install the Debian package with:\n\n```console\ncargo deb --install\n```\n\nNote, that when building a Debian package, the `--release` is passed to the\nbuild command already and you do not need to specify it yourself.  See for the\nflags that are set by default in `Cargo.toml`.\n\n## Building an RPM package\n\nYou can use the `cargo-generate-rpm` crate in order to build an RPM package from source.\nInstall it by:\n\n```console\ncargo install cargo-generate-rpm\n```\n\nThen you can build and install the RPM package with:\n\n```console\ncargo build --release\nstrip -s target/release/spotifyd\ncargo generate-rpm\nsudo rpm -Uvh target/generate-rpm/spotifyd-[VERSION].[ARCH].rpm\n```\n\n## Feature Flags\n\n`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`.\n\n| Feature Flag | Description                                                                         |\n|--------------|-------------------------------------------------------------------------------------|\n| `alsa_backend` | Provides support for the ALSA backend. Should work in most setups and is enabled by default. |\n| `pulseaudio_backend` | Support for PulseAudio. |\n| `rodio_backend` | Rust-native implementation of audio backends on all platforms. Does not need any external packages to be installed. |\n| `portaudio_backend` | Audio backend that can be used on non-Linux systems. |\n| `rodiojack_backend` | Support for the Jack backend. |\n| `dbus_mpris`   | Provides multimedia key support (Linux and BSD only)                                |\n\nTo customize your build, pass a subset of the features listed above to any of the `cargo` commands above via `--features <feature1>,<feature2>,...`. Disable the default feature `alsa_backend` with `--no-default-features`. So an example command could look like the following:\n\n```\ncargo install spotifyd --locked --no-default-features --features rodio_backend,dbus_mpris\n```\n"
  },
  {
    "path": "docs/src/troubleshooting.md",
    "content": "# Troubleshooting\n\n## no sound on FreeBSD\n\nIf 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.\n\nIf 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\n\n```bash\n- /dev/dsp0 (default)\n- /dev/dsp1\n- /dev/dsp2\n- /dev/dsp\n```\n\nAssume 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.\n\nAfter setting `device = \"/dev/dsp\"` in the config, the sound should start working. If not, you can try the other possible values that are available.\n"
  },
  {
    "path": "hooks/pre-commit",
    "content": "#!/bin/sh\n# Author: Sven Lechner (SirWindfield)\n# License: GPLv3\n\nrequire_clean_work_tree() {\n    # Update index\n    git update-index -q --ignore-submodules --refresh\n    err=0\n\n    # Disallow unstaged changes in the working tree\n    if ! git diff-files --quiet --ignore-submodules --; then\n        echo >&2 \"Cannot commit: you have unstaged changes.\"\n        git diff-files --name-status -r --ignore-submodules -- >&2\n        err=1\n    fi\n\n    if [ $err = 1 ]; then\n        echo >&2 \"Please stage or stash them.\"\n        exit 1\n    fi\n}\n\necho \"→ Checking for local changes...\"\nrequire_clean_work_tree\n\necho \"→ Formatting Rust code...\"\ncargo fmt\nif [ $? -ne 0 ]; then\n    exit 1\nfi\n\nfor path in $(git diff --name-only --cached); do\n    git update-index --add $path\ndone\n\necho \"→ Building pre-commit build artifacts...\"\ncargo check --quiet --no-default-features --features \"rodio_backend\"\nif [ $? -ne 0 ]; then\n    exit 1\nfi\ncargo build --quiet --no-default-features --features \"rodio_backend\"\n\n# Linting is only done with the rodio backend and the keyring feature as those should be \n# compilable for every supported platform without external library needs. \necho \"→ Linting Rust code...\"\ncargo clippy --no-default-features --features \"rodio_backend\" -- -D warnings\n\necho \"→ Testing Rust code...\"\ncargo test --no-default-features --features \"rodio_backend\"\n"
  },
  {
    "path": "setup-dev-workspace.sh",
    "content": "#!/bin/sh\n# Author: Sven Lechner (SirWindfield)\n# License: GPLv3\n\n# Copies all hooks into the .git/hooks directory\ncp hooks/* .git/hooks\n"
  },
  {
    "path": "src/alsa_mixer.rs",
    "content": "use alsa::device_name::HintIter;\nuse color_eyre::{\n    Section,\n    eyre::{self, Context, eyre},\n};\nuse librespot_playback::mixer::{Mixer, MixerConfig};\nuse log::error;\nuse std::sync::{Arc, Mutex, MutexGuard};\n\npub fn get_available_controls() -> alsa::Result<HintIter> {\n    alsa::device_name::HintIter::new_str(None, \"ctl\")\n}\n\npub struct AlsaMixer {\n    pub mixer: Arc<Mutex<alsa::Mixer>>,\n    pub config: MixerConfig,\n}\n\nimpl AlsaMixer {\n    fn get_selem<'a>(\n        &'a self,\n        lock: &'a MutexGuard<'a, alsa::Mixer>,\n    ) -> eyre::Result<alsa::mixer::Selem<'a>> {\n        let selem_id = alsa::mixer::SelemId::new(&self.config.control, self.config.index);\n        let selem = lock.find_selem(&selem_id).ok_or_else(|| {\n            eyre!(\n                \"No control with name '{}' in alsa device '{}'\",\n                self.config.control,\n                self.config.device,\n            )\n            .with_suggestion(|| {\n                format!(\n                    \"maybe try one of the following for 'control':{}\",\n                    lock.iter()\n                        .filter_map(|elem| {\n                            let selem = alsa::mixer::Selem::new(elem)?;\n                            if selem.has_playback_volume() {\n                                selem\n                                    .get_id()\n                                    .get_name()\n                                    .ok()\n                                    .map(|name| format!(\"\\n- {name}\"))\n                            } else {\n                                None\n                            }\n                        })\n                        .collect::<String>()\n                )\n            })\n        })?;\n        Ok(selem)\n    }\n    fn set_volume_with_err(&self, volume: u16) -> eyre::Result<()> {\n        let lock = self.mixer.lock().expect(\"lock shouldn't be poisoned\");\n        let elem = self.get_selem(&lock)?;\n        let (min, max) = elem.get_playback_volume_range();\n\n        let volume_steps = (max - min) as f64;\n        let normalised_volume = if matches!(\n            self.config.volume_ctrl,\n            librespot_playback::config::VolumeCtrl::Linear\n        ) {\n            (((volume as f64) / (u16::MAX as f64)) * volume_steps) as i64 + min\n        } else {\n            ((volume as f64 + 1.0).log((u16::MAX as f64) + 1.0) * volume_steps).floor() as i64 + min\n        };\n\n        elem.set_playback_volume_all(normalised_volume)?;\n        Ok(())\n    }\n\n    fn get_volume_with_err(&self) -> eyre::Result<u16> {\n        let lock = self.mixer.lock().expect(\"lock shouldn't be poisoned\");\n        let elem = self.get_selem(&lock)?;\n        let (min, max) = elem.get_playback_volume_range();\n        let volume_steps = (max - min) as f64;\n        let vol = elem.get_playback_volume(alsa::mixer::SelemChannelId::mono())?;\n        let normalized_volume = if matches!(\n            self.config.volume_ctrl,\n            librespot_playback::config::VolumeCtrl::Linear\n        ) {\n            ((vol - min) as f64 * u16::MAX as f64 / volume_steps).floor() as u16\n        } else {\n            ((u16::MAX as f64 + 1.0).powf(((vol - min) as f64) / volume_steps) - 1.0).floor() as u16\n        };\n        Ok(normalized_volume)\n    }\n}\n\nimpl Mixer for AlsaMixer {\n    fn open(config: MixerConfig) -> Result<AlsaMixer, librespot_core::Error> {\n        let mixer = alsa::Mixer::new(&config.device, false)\n            .wrap_err(\"failed to open mixer\")\n            .map_err(librespot_core::Error::invalid_argument)?;\n        Ok(AlsaMixer {\n            mixer: Arc::new(Mutex::new(mixer)),\n            config,\n        })\n    }\n\n    fn volume(&self) -> u16 {\n        match self.get_volume_with_err() {\n            Ok(vol) => vol,\n            Err(err) => {\n                error!(\"failed to get volume from alsa device: {err:?}\");\n                0\n            }\n        }\n    }\n\n    fn set_volume(&self, volume: u16) {\n        match self.set_volume_with_err(volume) {\n            Ok(_) => (),\n            Err(err) => error!(\"Couldn't set volume of alsa device: {err:?}\"),\n        }\n    }\n}\n"
  },
  {
    "path": "src/config.rs",
    "content": "use crate::utils;\nuse clap::{\n    Args, Parser, Subcommand, ValueEnum,\n    builder::{IntoResettable, PossibleValuesParser, TypedValueParser, ValueParser},\n};\nuse color_eyre::{\n    Report,\n    eyre::{Context, bail},\n};\nuse directories::ProjectDirs;\nuse gethostname::gethostname;\nuse librespot_core::{cache::Cache, config::DeviceType as LSDeviceType, config::SessionConfig};\nuse librespot_playback::{\n    audio_backend,\n    config::{AudioFormat as LSAudioFormat, Bitrate as LSBitrate, PlayerConfig},\n    dither::{DithererBuilder, TriangularDitherer, mk_ditherer},\n};\nuse log::{debug, error, info, warn};\nuse serde::{\n    Deserialize, Deserializer,\n    de::{self, Error, Unexpected},\n};\nuse sha1::{Digest, Sha1};\nuse std::{\n    borrow::Cow,\n    convert::TryInto,\n    fs,\n    path::{Path, PathBuf},\n    str::FromStr,\n};\nuse url::Url;\n\nconst CONFIG_FILE_NAME: &str = \"spotifyd.conf\";\n\n#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, ValueEnum)]\n#[serde(rename_all = \"snake_case\")]\npub enum VolumeController {\n    #[cfg(feature = \"alsa_backend\")]\n    Alsa,\n    #[cfg(feature = \"alsa_backend\")]\n    AlsaLinear,\n    #[serde(rename = \"softvol\")]\n    SoftVolume,\n    None,\n}\n\n// Spotify's device type (copied from it's config.rs)\n#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, ValueEnum)]\n#[serde(rename_all = \"snake_case\")]\npub enum DeviceType {\n    Unknown,\n    Computer,\n    Tablet,\n    Smartphone,\n    Speaker,\n    #[serde(rename = \"t_v\")]\n    Tv,\n    #[serde(rename = \"a_v_r\")]\n    Avr,\n    #[serde(rename = \"s_t_b\")]\n    Stb,\n    AudioDongle,\n    GameConsole,\n    CastAudio,\n    CastVideo,\n    Automobile,\n    Smartwatch,\n    Chromebook,\n    UnknownSpotify,\n    CarThing,\n    Observer,\n}\n\nimpl From<DeviceType> for LSDeviceType {\n    fn from(item: DeviceType) -> Self {\n        match item {\n            DeviceType::Unknown => LSDeviceType::Unknown,\n            DeviceType::Computer => LSDeviceType::Computer,\n            DeviceType::Tablet => LSDeviceType::Tablet,\n            DeviceType::Smartphone => LSDeviceType::Smartphone,\n            DeviceType::Speaker => LSDeviceType::Speaker,\n            DeviceType::Tv => LSDeviceType::Tv,\n            DeviceType::Avr => LSDeviceType::Avr,\n            DeviceType::Stb => LSDeviceType::Stb,\n            DeviceType::AudioDongle => LSDeviceType::AudioDongle,\n            DeviceType::GameConsole => LSDeviceType::GameConsole,\n            DeviceType::CastAudio => LSDeviceType::CastAudio,\n            DeviceType::CastVideo => LSDeviceType::CastVideo,\n            DeviceType::Automobile => LSDeviceType::Automobile,\n            DeviceType::Smartwatch => LSDeviceType::Smartwatch,\n            DeviceType::Chromebook => LSDeviceType::Chromebook,\n            DeviceType::UnknownSpotify => LSDeviceType::UnknownSpotify,\n            DeviceType::CarThing => LSDeviceType::CarThing,\n            DeviceType::Observer => LSDeviceType::Observer,\n        }\n    }\n}\n\nfn bitrate_parser() -> impl IntoResettable<ValueParser> {\n    let possible_values: PossibleValuesParser = [\"96\", \"160\", \"320\"].into();\n    possible_values.map(|val| match val.as_str() {\n        \"96\" => Bitrate::Bitrate96,\n        \"160\" => Bitrate::Bitrate160,\n        \"320\" => Bitrate::Bitrate320,\n        _ => unreachable!(),\n    })\n}\n\n/// Spotify's audio bitrate\n#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]\npub enum Bitrate {\n    Bitrate96,\n    Bitrate160,\n    Bitrate320,\n}\n\nimpl<'de> Deserialize<'de> for Bitrate {\n    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n        match u16::deserialize(deserializer) {\n            Ok(96) => Ok(Self::Bitrate96),\n            Ok(160) => Ok(Self::Bitrate160),\n            Ok(320) => Ok(Self::Bitrate320),\n            Ok(x) => Err(D::Error::invalid_value(\n                Unexpected::Unsigned(x.into()),\n                &\"a bitrate: 96, 160, 320\",\n            )),\n            Err(e) => Err(e),\n        }\n    }\n}\n\nimpl From<Bitrate> for LSBitrate {\n    fn from(bitrate: Bitrate) -> Self {\n        match bitrate {\n            Bitrate::Bitrate96 => LSBitrate::Bitrate96,\n            Bitrate::Bitrate160 => LSBitrate::Bitrate160,\n            Bitrate::Bitrate320 => LSBitrate::Bitrate320,\n        }\n    }\n}\n\n#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, ValueEnum)]\n#[serde(rename_all = \"snake_case\")]\npub enum DBusType {\n    Session,\n    System,\n}\n\n#[derive(Clone, Copy, Debug, Deserialize, PartialEq, ValueEnum)]\npub enum AudioFormat {\n    F32,\n    S32,\n    S24,\n    S24_3,\n    S16,\n}\n\nimpl From<AudioFormat> for LSAudioFormat {\n    fn from(audio_format: AudioFormat) -> Self {\n        match audio_format {\n            AudioFormat::F32 => LSAudioFormat::F32,\n            AudioFormat::S32 => LSAudioFormat::S32,\n            AudioFormat::S24 => LSAudioFormat::S24,\n            AudioFormat::S24_3 => LSAudioFormat::S24_3,\n            AudioFormat::S16 => LSAudioFormat::S16,\n        }\n    }\n}\n\nfn possible_backends() -> Vec<&'static str> {\n    audio_backend::BACKENDS.iter().map(|b| b.0).collect()\n}\n\nfn deserialize_backend<'de, D>(de: D) -> Result<Option<String>, D::Error>\nwhere\n    D: Deserializer<'de>,\n{\n    let backend = String::deserialize(de)?;\n    let possible_backends = possible_backends();\n    if possible_backends.contains(&backend.as_str()) {\n        Ok(Some(backend))\n    } else {\n        Err(de::Error::invalid_value(\n            Unexpected::Str(&backend),\n            &format!(\n                \"a valid backend (available: {})\",\n                possible_backends.join(\", \")\n            )\n            .as_str(),\n        ))\n    }\n}\n\nfn number_or_string<'de, D>(de: D) -> Result<Option<u8>, D::Error>\nwhere\n    D: Deserializer<'de>,\n{\n    let val = toml::Value::deserialize(de)?;\n\n    let unexpected = match val {\n        toml::Value::Integer(num) => {\n            let num: u8 = num.try_into().map_err(de::Error::custom)?;\n            return Ok(Some(num));\n        }\n        toml::Value::String(num) => {\n            return u8::from_str(&num)\n                .map(Some)\n                .inspect(|_| warn!(\"`initial_volume` should be a number rather than a string, this will become a hard error in the future\"))\n                .map_err(de::Error::custom)\n        }\n        toml::Value::Float(f) => Unexpected::Float(f),\n        toml::Value::Boolean(b) => Unexpected::Bool(b),\n        toml::Value::Datetime(_) => Unexpected::Other(\"datetime\"),\n        toml::Value::Array(_) => Unexpected::Seq,\n        toml::Value::Table(_) => Unexpected::Map,\n    };\n    Err(de::Error::invalid_type(unexpected, &\"number\"))\n}\n\n#[derive(Debug, Default, Parser)]\n#[command(version, about, long_about = None, args_conflicts_with_subcommands = true)]\npub struct CliConfig {\n    /// The path to the config file to use\n    #[arg(long, value_name = \"PATH\", global = true)]\n    pub config_path: Option<PathBuf>,\n\n    /// Prints more verbose output\n    #[arg(short, long, action = clap::ArgAction::Count, global = true)]\n    pub verbose: u8,\n\n    /// If set, starts spotifyd without detaching\n    #[arg(long)]\n    pub no_daemon: bool,\n\n    /// Path to PID file.\n    #[cfg(unix)]\n    #[arg(long, value_name = \"PATH\")]\n    pub pid: Option<PathBuf>,\n\n    #[command(subcommand)]\n    pub mode: Option<ExecutionMode>,\n\n    #[command(flatten)]\n    pub shared_config: SharedConfigValues,\n}\n\n#[derive(Debug, Subcommand)]\npub enum ExecutionMode {\n    #[command(visible_alias = \"auth\")]\n    Authenticate {\n        /// The port to use for the OAuth redirect\n        #[arg(long, default_value_t = 8000)]\n        oauth_port: u16,\n    },\n}\n\n// A struct that holds all allowed config fields.\n// The actual config file is made up of two sections, spotifyd and global.\n#[derive(Clone, Default, Debug, Deserialize, PartialEq, Args)]\npub struct SharedConfigValues {\n    /// A script that gets evaluated in the user's shell when the song changes\n    #[arg(visible_alias = \"onevent\", long, value_name = \"CMD\")]\n    #[serde(alias = \"onevent\")]\n    on_song_change_hook: Option<String>,\n\n    /// The cache path used to store credentials and music file artifacts\n    #[arg(long, short, value_name = \"PATH\", global = true)]\n    cache_path: Option<PathBuf>,\n\n    /// The maximal cache size in bytes\n    #[arg(long, value_name = \"BYTES\")]\n    max_cache_size: Option<u64>,\n\n    /// Disable the use of audio cache\n    #[arg(\n        long,\n        default_missing_value(\"true\"),\n        require_equals = true,\n        num_args(0..=1),\n        value_name = \"BOOL\"\n    )]\n    no_audio_cache: Option<bool>,\n\n    /// The audio backend to use\n    #[arg(long, short, value_parser = possible_backends())]\n    #[serde(deserialize_with = \"deserialize_backend\", default)]\n    backend: Option<String>,\n\n    /// The volume controller to use\n    #[arg(value_enum, long, visible_alias = \"volume-control\")]\n    #[serde(alias = \"volume-control\")]\n    volume_controller: Option<VolumeController>,\n\n    /// The audio device (or pipe file)\n    #[arg(long)]\n    device: Option<String>,\n\n    /// The device name displayed in Spotify\n    #[arg(long, short)]\n    device_name: Option<String>,\n\n    /// The bitrate of the streamed audio data\n    #[arg(long, short = 'B', value_parser = bitrate_parser())]\n    bitrate: Option<Bitrate>,\n\n    /// The audio format of the streamed audio data\n    #[arg(value_enum, long)]\n    audio_format: Option<AudioFormat>,\n\n    /// Initial volume between 0 and 100\n    #[arg(long)]\n    #[serde(deserialize_with = \"number_or_string\", default)]\n    initial_volume: Option<u8>,\n\n    /// Enable to normalize the volume during playback\n    #[arg(\n        long,\n        default_missing_value(\"true\"),\n        require_equals = true,\n        num_args(0..=1),\n        value_name = \"BOOL\"\n    )]\n    volume_normalisation: Option<bool>,\n\n    /// A custom pregain applied before sending the audio to the output device\n    #[arg(long)]\n    normalisation_pregain: Option<f64>,\n\n    #[arg(\n        long,\n        default_missing_value(\"true\"),\n        require_equals = true,\n        num_args(0..=1),\n        value_name = \"BOOL\"\n    )]\n    disable_discovery: Option<bool>,\n\n    /// The port used for the Spotify Connect discovery\n    #[arg(long)]\n    zeroconf_port: Option<u16>,\n\n    /// The proxy used to connect to spotify's servers\n    #[arg(long, value_name = \"URL\")]\n    proxy: Option<String>,\n\n    /// The device type shown to clients\n    #[arg(value_enum, long)]\n    device_type: Option<DeviceType>,\n\n    /// Start playing similar songs after your music has ended\n    #[arg(\n        long,\n        default_missing_value(\"true\"),\n        require_equals = true,\n        num_args(0..=1),\n        value_name = \"BOOL\"\n    )]\n    #[serde(default)]\n    autoplay: Option<bool>,\n\n    #[cfg(feature = \"alsa_backend\")]\n    #[command(flatten)]\n    #[serde(flatten)]\n    alsa_config: AlsaConfig,\n\n    #[cfg(feature = \"dbus_mpris\")]\n    #[command(flatten)]\n    #[serde(flatten)]\n    mpris_config: MprisConfig,\n}\n\n#[cfg(feature = \"dbus_mpris\")]\n#[derive(Debug, Default, Clone, Deserialize, Args, PartialEq, Eq)]\npub struct MprisConfig {\n    /// Enables the MPRIS interface\n    #[arg(\n        long,\n        default_missing_value(\"true\"),\n        require_equals = true,\n        num_args(0..=1),\n        value_name = \"BOOL\"\n    )]\n    #[serde(alias = \"use-mpris\")]\n    pub(crate) use_mpris: Option<bool>,\n\n    /// The Bus-type to use for the MPRIS interface\n    #[arg(value_enum, long)]\n    pub(crate) dbus_type: Option<DBusType>,\n}\n\n#[cfg(feature = \"alsa_backend\")]\n#[derive(Debug, Default, Clone, Deserialize, Args, PartialEq, Eq)]\npub struct AlsaConfig {\n    /// The control device\n    #[arg(long)]\n    pub(crate) control: Option<String>,\n\n    /// The mixer to use\n    #[arg(long)]\n    pub(crate) mixer: Option<String>,\n}\n\n#[derive(Debug, Default, Deserialize)]\npub struct FileConfig {\n    global: Option<SharedConfigValues>,\n    spotifyd: Option<SharedConfigValues>,\n}\n\nimpl FileConfig {\n    pub fn get_merged_sections(self) -> Option<SharedConfigValues> {\n        match (self.global, self.spotifyd) {\n            (Some(global), Some(mut spotifyd)) => {\n                spotifyd.merge_with(global);\n                Some(spotifyd)\n            }\n            (global, spotifyd) => global.or(spotifyd),\n        }\n    }\n}\n\n#[derive(Copy, Clone)]\nenum KnownConfigProblem {\n    #[cfg_attr(\n        all(feature = \"alsa_backend\", feature = \"dbus_mpris\"),\n        expect(dead_code)\n    )]\n    MissingFeature(&'static str),\n    UsernamePassword,\n}\n\nfn get_known_config_problem(path: &serde_ignored::Path<'_>) -> Option<KnownConfigProblem> {\n    const DISABLED_CONFIGS: &[(KnownConfigProblem, &[&str])] = &[\n        #[cfg(not(feature = \"alsa_backend\"))]\n        (\n            KnownConfigProblem::MissingFeature(\"alsa_backend\"),\n            &[\"control\", \"mixer\"],\n        ),\n        #[cfg(not(feature = \"dbus_mpris\"))]\n        (\n            KnownConfigProblem::MissingFeature(\"dbus_mpris\"),\n            &[\"use_mpris\", \"dbus_type\"],\n        ),\n        (\n            KnownConfigProblem::UsernamePassword,\n            &[\n                \"username\",\n                \"password\",\n                \"username_cmd\",\n                \"password_cmd\",\n                \"use_keyring\",\n            ],\n        ),\n    ];\n\n    if let serde_ignored::Path::Map { key, .. } = path {\n        for (problem, params) in DISABLED_CONFIGS {\n            if params.contains(&key.as_str()) {\n                return Some(*problem);\n            }\n        }\n    }\n    None\n}\n\nimpl CliConfig {\n    pub fn load_config_file_values(&mut self) -> Result<(), Report> {\n        let config_file_path = match self.config_path.clone().or_else(get_config_file) {\n            Some(p) => p,\n            None => {\n                info!(\"No config file specified. Running with default values\");\n                return Ok(());\n            }\n        };\n        info!(\"Loading config from {:?}\", &config_file_path);\n\n        let content = match fs::read_to_string(config_file_path) {\n            Ok(s) => s,\n            Err(e) => {\n                info!(\"Failed reading config file: {}\", e);\n                return Ok(());\n            }\n        };\n\n        let toml_de = toml::Deserializer::parse(&content)?;\n        let config_content: FileConfig = serde_ignored::deserialize(toml_de, |path| {\n            if let Some(problem) = get_known_config_problem(&path) {\n                match problem {\n                    KnownConfigProblem::MissingFeature(feature) => {\n                        warn!(\n                            \"The config key '{path}' is ignored, because the feature '{feature}' is missing in this build\"\n                        );\n                    }\n                    KnownConfigProblem::UsernamePassword => {\n                        warn!(\n                            \"The config key '{path}' is ignored, because authentication with username and password is no longer supported by Spotify. Please use `spotifyd authenticate` instead\"\n                        );\n                    }\n                }\n            } else {\n                warn!(\"Unknown key '{path}' in config will be ignored\");\n            }\n        })?;\n\n        // The call to get_merged_sections consumes the FileConfig!\n        if let Some(merged_sections) = config_content.get_merged_sections() {\n            self.shared_config.merge_with(merged_sections);\n        }\n\n        Ok(())\n    }\n}\n\nimpl SharedConfigValues {\n    pub fn get_cache(&self, for_oauth: bool) -> color_eyre::Result<Cache> {\n        let Some(cache_path) = self.cache_path.as_deref().map(Cow::Borrowed).or_else(|| {\n            ProjectDirs::from(\"\", \"\", \"spotifyd\")\n                .map(|dirs| Cow::Owned(dirs.cache_dir().to_path_buf()))\n        }) else {\n            bail!(\"Failed to determine cache directory, please specify one manually\");\n        };\n\n        if for_oauth {\n            let mut creds_path = cache_path.into_owned();\n            creds_path.push(\"oauth\");\n            Cache::new(Some(creds_path), None, None, None)\n        } else {\n            let audio_cache = !self.no_audio_cache.unwrap_or(false);\n\n            let mut creds_path = cache_path.to_path_buf();\n            creds_path.push(\"zeroconf\");\n            Cache::new(\n                Some(creds_path.as_path()),\n                Some(cache_path.as_ref()),\n                audio_cache.then_some(cache_path.as_ref()),\n                self.max_cache_size,\n            )\n        }\n        .wrap_err(\"Failed to initialize cache\")\n    }\n\n    pub fn proxy_url(&self) -> Option<Url> {\n        match &self.proxy {\n            Some(s) => match Url::parse(s) {\n                Ok(url) => {\n                    if url.scheme() != \"http\" {\n                        error!(\"Only HTTP proxies are supported!\");\n                        None\n                    } else {\n                        Some(url)\n                    }\n                }\n                Err(err) => {\n                    error!(\"Invalid proxy URL: {}\", err);\n                    None\n                }\n            },\n            None => {\n                debug!(\"No proxy specified\");\n                None\n            }\n        }\n    }\n\n    pub fn merge_with(&mut self, mut other: SharedConfigValues) {\n        macro_rules! merge {\n            ($a:expr; and $b:expr => {$($x:ident),+}) => {\n                $($a.$x = $a.$x.take().or_else(|| $b.$x.take());)+\n            }\n        }\n\n        // Handles Option<T> merging.\n        merge!(self; and other => {\n            backend,\n            volume_normalisation,\n            normalisation_pregain,\n            bitrate,\n            initial_volume,\n            device_name,\n            device,\n            volume_controller,\n            cache_path,\n            no_audio_cache,\n            on_song_change_hook,\n            disable_discovery,\n            zeroconf_port,\n            proxy,\n            device_type,\n            max_cache_size,\n            audio_format,\n            autoplay\n        });\n\n        #[cfg(feature = \"dbus_mpris\")]\n        merge!(self.mpris_config; and other.mpris_config => {use_mpris, dbus_type});\n        #[cfg(feature = \"alsa_backend\")]\n        merge!(self.alsa_config; and other.alsa_config => {mixer, control});\n    }\n}\n\npub(crate) fn get_config_file() -> Option<PathBuf> {\n    let etc_conf = format!(\"/etc/{CONFIG_FILE_NAME}\");\n    let dirs = directories::ProjectDirs::from(\"\", \"\", \"spotifyd\")?;\n    let mut path = dirs.config_dir().to_path_buf();\n    path.push(CONFIG_FILE_NAME);\n\n    if path.exists() {\n        Some(path)\n    } else if Path::new(&etc_conf).exists() {\n        let path: PathBuf = etc_conf.into();\n        Some(path)\n    } else {\n        None\n    }\n}\n\nfn device_id(name: &str) -> String {\n    hex::encode(Sha1::digest(name.as_bytes()))\n}\n\npub(crate) struct SpotifydConfig {\n    pub(crate) cache: Option<Cache>,\n    pub(crate) oauth_cache: Option<Cache>,\n    pub(crate) backend: Option<String>,\n    pub(crate) audio_device: Option<String>,\n    pub(crate) audio_format: LSAudioFormat,\n    pub(crate) volume_controller: VolumeController,\n    pub(crate) initial_volume: u16,\n    pub(crate) device_name: String,\n    pub(crate) player_config: PlayerConfig,\n    pub(crate) session_config: SessionConfig,\n    pub(crate) onevent: Option<String>,\n    #[cfg(unix)]\n    pub(crate) pid: Option<String>,\n    pub(crate) shell: String,\n    pub(crate) discovery: bool,\n    pub(crate) zeroconf_port: Option<u16>,\n    pub(crate) device_type: LSDeviceType,\n    #[cfg(feature = \"dbus_mpris\")]\n    pub(crate) mpris: MprisConfig,\n    #[cfg(feature = \"alsa_backend\")]\n    pub(crate) alsa_config: AlsaConfig,\n}\n\npub(crate) fn get_internal_config(config: CliConfig) -> SpotifydConfig {\n    let (cache, oauth_cache) = match (\n        config.shared_config.get_cache(false),\n        config.shared_config.get_cache(true),\n    ) {\n        (Ok(cache), Ok(oauth_cache)) => (Some(cache), Some(oauth_cache)),\n        (a, b) => {\n            // at least one of the results are err\n            let err = a.or(b).map(|_| ()).unwrap_err();\n            warn!(\"{err}\");\n            (None, None)\n        }\n    };\n    let proxy_url = config.shared_config.proxy_url();\n\n    let bitrate: LSBitrate = config\n        .shared_config\n        .bitrate\n        .unwrap_or(Bitrate::Bitrate160)\n        .into();\n\n    let audio_format: LSAudioFormat = config\n        .shared_config\n        .audio_format\n        .unwrap_or(AudioFormat::S16)\n        .into();\n\n    let volume_controller = config\n        .shared_config\n        .volume_controller\n        .unwrap_or(VolumeController::SoftVolume);\n\n    let default_initial_volume = 90;\n    let initial_volume: u16 = config\n        .shared_config\n        .initial_volume\n        .filter(|val| {\n            if (0..=100).contains(val) {\n                true\n            } else {\n                warn!(\"initial_volume must be in range 0..100\");\n                false\n            }\n        })\n        .map(|volume| (volume as i32 * (u16::MAX as i32) / 100) as u16)\n        .unwrap_or((default_initial_volume * (u16::MAX as i32) / 100) as u16);\n\n    let device_name = config\n        .shared_config\n        .device_name\n        .filter(|s| !s.trim().is_empty())\n        .unwrap_or_else(|| format!(\"{}@{}\", \"Spotifyd\", gethostname().to_string_lossy()));\n\n    let device_id = device_id(&device_name);\n\n    let normalisation_pregain = config.shared_config.normalisation_pregain.unwrap_or(0.0);\n\n    let device_type = config\n        .shared_config\n        .device_type\n        .unwrap_or(DeviceType::Speaker)\n        .into();\n\n    #[cfg(unix)]\n    let pid = config.pid.map(|f| {\n        f.into_os_string()\n            .into_string()\n            .expect(\"Failed to convert PID file path to valid Unicode\")\n    });\n\n    let shell = utils::get_shell().unwrap_or_else(|| {\n        info!(\"Unable to identify shell. Defaulting to \\\"sh\\\".\");\n        \"sh\".to_string()\n    });\n\n    // choose default ditherer the same way librespot does\n    let ditherer: Option<DithererBuilder> = match audio_format {\n        LSAudioFormat::S16 | LSAudioFormat::S24 | LSAudioFormat::S24_3 => {\n            Some(mk_ditherer::<TriangularDitherer>)\n        }\n        _ => None,\n    };\n\n    // TODO: when we were on librespot 0.1.5, all PlayerConfig values were available in the\n    //  Spotifyd config. The upgrade to librespot 0.2.0 introduces new config variables, and we\n    //  should consider adding them to Spotifyd's config system.\n    let pc = PlayerConfig {\n        bitrate,\n        normalisation: config.shared_config.volume_normalisation.unwrap_or(false),\n        normalisation_pregain_db: normalisation_pregain,\n        gapless: true,\n        ditherer,\n        ..Default::default()\n    };\n\n    SpotifydConfig {\n        cache,\n        oauth_cache,\n        backend: config.shared_config.backend,\n        audio_device: config.shared_config.device,\n        audio_format,\n        volume_controller,\n        initial_volume,\n        device_name,\n        player_config: pc,\n        session_config: SessionConfig {\n            autoplay: config.shared_config.autoplay,\n            device_id,\n            proxy: proxy_url,\n            ap_port: Some(443),\n            ..Default::default()\n        },\n        onevent: config.shared_config.on_song_change_hook,\n        shell,\n        discovery: !config.shared_config.disable_discovery.unwrap_or(false),\n        zeroconf_port: config.shared_config.zeroconf_port,\n        device_type,\n        #[cfg(unix)]\n        pid,\n        #[cfg(feature = \"dbus_mpris\")]\n        mpris: config.shared_config.mpris_config,\n        #[cfg(feature = \"alsa_backend\")]\n        alsa_config: config.shared_config.alsa_config,\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_section_merging() {\n        let mut spotifyd_section = SharedConfigValues {\n            device_type: Some(DeviceType::Computer),\n            ..Default::default()\n        };\n\n        let global_section = SharedConfigValues {\n            device_name: Some(\"spotifyd-test\".to_string()),\n            ..Default::default()\n        };\n\n        // The test only makes sense if both sections differ.\n        assert_ne!(spotifyd_section, global_section);\n\n        let file_config = FileConfig {\n            global: Some(global_section),\n            spotifyd: Some(spotifyd_section.clone()),\n        };\n        let merged_config = file_config.get_merged_sections().unwrap();\n\n        // Add the new field to spotifyd section.\n        spotifyd_section.device_name = Some(\"spotifyd-test\".to_string());\n        assert_eq!(merged_config, spotifyd_section);\n    }\n\n    #[test]\n    fn test_example_config() {\n        let example_config = include_str!(\"../contrib/spotifyd.conf\");\n\n        let config: FileConfig = toml::Deserializer::parse(example_config)\n            .and_then(|toml_de| {\n                serde_ignored::deserialize(toml_de, |path| {\n                    panic!(\"Unknown key in (commented) example config: '{}'\", path)\n                })\n            })\n            .expect(\"Commented example config should be valid\");\n\n        assert_eq!(\n            (config.global, config.spotifyd),\n            (Some(SharedConfigValues::default()), None),\n            \"example config should not do anything by default, but contain the global section\"\n        );\n\n        let uncommented_example_config = example_config\n            .lines()\n            .map(|line| {\n                // uncomment any line starting with #[a-zA-Z]\n                line.strip_prefix(\"#\")\n                    .filter(|rest| {\n                        // uncomment if the rest is a valid config line\n                        // if alsa_backend is not enabled, ignore the 'backend = \"alsa\"' line\n                        rest.starts_with(char::is_alphabetic)\n                            && (cfg!(feature = \"alsa_backend\") || !rest.starts_with(\"backend\"))\n                    })\n                    .unwrap_or(line)\n            })\n            .collect::<Vec<&str>>()\n            .join(\"\\n\");\n\n        let config: FileConfig = toml::Deserializer::parse(&uncommented_example_config)\n            .and_then(|toml_de| {\n                serde_ignored::deserialize(toml_de, |path| {\n                    if !matches!(\n                        get_known_config_problem(&path),\n                        Some(KnownConfigProblem::MissingFeature(_))\n                    ) {\n                        panic!(\"Unknown configuration key in example config: {}\", path);\n                    }\n                })\n            })\n            .expect(\"Uncommented example config should be valid\");\n\n        assert!(\n            config.spotifyd.is_none(),\n            \"example config should not have a spotifyd section\"\n        );\n        assert!(\n            config\n                .global\n                .is_some_and(|global| global != SharedConfigValues::default()),\n            \"uncommented example config should contain some values\"\n        );\n    }\n}\n"
  },
  {
    "path": "src/dbus_mpris.rs",
    "content": "use crate::config::DBusType;\nuse chrono::{Duration, prelude::*};\nuse dbus::{\n    MethodErr,\n    arg::{RefArg, Variant},\n    channel::{MatchingReceiver, Sender},\n    message::{MatchRule, SignalArgs},\n    nonblock::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged,\n};\nuse dbus_crossroads::{Crossroads, IfaceToken};\nuse dbus_tokio::connection::{self, IOResourceError};\nuse futures::{\n    Future,\n    task::{Context, Poll},\n};\nuse librespot_connect::{LoadContextOptions, LoadRequest, LoadRequestOptions, Spirc};\nuse librespot_core::{Session, SpotifyUri};\nuse librespot_metadata::audio::AudioItem;\nuse librespot_playback::player::PlayerEvent;\nuse log::{debug, warn};\nuse std::convert::TryFrom;\nuse std::{\n    collections::HashMap,\n    pin::Pin,\n    sync::{Arc, RwLock},\n};\nuse thiserror::Error;\nuse time::format_description::well_known::Iso8601;\nuse tokio::{\n    runtime::Handle,\n    sync::{\n        Mutex,\n        mpsc::{UnboundedReceiver, UnboundedSender},\n    },\n};\n\ntype DbusMap = HashMap<String, Variant<Box<dyn RefArg>>>;\n\nconst MPRIS_PATH: &str = \"/org/mpris/MediaPlayer2\";\nconst CONTROLS_PATH: &str = \"/rs/spotifyd/Controls\";\n\npub enum ControlMessage {\n    SetSession(Arc<Spirc>, Session),\n    DropSession,\n    Shutdown,\n}\n\npub(crate) struct DbusServer {\n    dbus_future: Pin<Box<dyn Future<Output = Result<(), DbusError>>>>,\n    control_tx: UnboundedSender<ControlMessage>,\n}\n\nimpl DbusServer {\n    pub fn new(event_rx: UnboundedReceiver<PlayerEvent>, dbus_type: DBusType) -> DbusServer {\n        let (control_tx, control_rx) = tokio::sync::mpsc::unbounded_channel();\n        let dbus_future = Box::pin(create_dbus_server(event_rx, control_rx, dbus_type));\n        DbusServer {\n            dbus_future,\n            control_tx,\n        }\n    }\n\n    pub fn set_session(&self, spirc: Arc<Spirc>, session: Session) -> Result<(), DbusError> {\n        self.control_tx\n            .send(ControlMessage::SetSession(spirc, session))\n            .map_err(|_| DbusError::ControlChannelBroken)\n    }\n\n    pub fn drop_session(&self) -> Result<(), DbusError> {\n        self.control_tx\n            .send(ControlMessage::DropSession)\n            .map_err(|_| DbusError::ControlChannelBroken)\n    }\n\n    /// Sends a shutdown signal and returns false, if the server was already shut down.\n    pub fn shutdown(&self) -> bool {\n        self.control_tx.send(ControlMessage::Shutdown).is_ok()\n    }\n}\n\n#[derive(Debug, Error)]\npub(crate) enum DbusError {\n    #[error(\"Failed to initialize D-Bus: {}\", .0)]\n    InitFailure(#[from] dbus::Error),\n    #[error(\"The connection was terminated unexpectedly: {}\", .0)]\n    ConnectionFailure(#[from] IOResourceError),\n    #[error(\"Unexpectedly lost control of dbus server\")]\n    ControlChannelBroken,\n}\n\nimpl Future for DbusServer {\n    type Output = Result<(), DbusError>;\n\n    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n        self.dbus_future.as_mut().poll(cx)\n    }\n}\n\n#[derive(Clone, Copy, PartialEq, Eq, Debug)]\nenum PlaybackStatus {\n    Playing,\n    Paused,\n    Stopped,\n}\n\nimpl PlaybackStatus {\n    fn to_mpris(self) -> &'static str {\n        match self {\n            PlaybackStatus::Playing => \"Playing\",\n            PlaybackStatus::Paused => \"Paused\",\n            PlaybackStatus::Stopped => \"Stopped\",\n        }\n    }\n}\n\n#[derive(Debug)]\nstruct Position {\n    last_position: Duration,\n    last_update: DateTime<Local>,\n}\n\nimpl Position {\n    fn new() -> Self {\n        Self {\n            last_position: Duration::zero(),\n            last_update: Local::now(),\n        }\n    }\n    fn update_position(&mut self, new_position: Duration) {\n        self.last_update = Local::now();\n        self.last_position = new_position;\n    }\n\n    fn get_position(&self) -> Duration {\n        (Local::now() - self.last_update) + self.last_position\n    }\n}\n\n#[derive(Clone, Copy, Debug)]\nenum RepeatState {\n    None,\n    Track,\n    All,\n}\n\nimpl RepeatState {\n    fn to_mpris(self) -> &'static str {\n        match self {\n            RepeatState::None => \"None\",\n            RepeatState::Track => \"Track\",\n            RepeatState::All => \"Playlist\",\n        }\n    }\n\n    fn repeat_track(self) -> bool {\n        matches!(self, RepeatState::Track)\n    }\n\n    fn repeat_context(self) -> bool {\n        !matches!(self, RepeatState::None)\n    }\n}\n\nimpl From<(bool, bool)> for RepeatState {\n    fn from((context, track): (bool, bool)) -> Self {\n        if context {\n            if track {\n                RepeatState::Track\n            } else {\n                RepeatState::All\n            }\n        } else {\n            RepeatState::None\n        }\n    }\n}\n\n#[derive(Debug)]\nstruct CurrentStateInner {\n    status: PlaybackStatus,\n    position: Option<Position>,\n    audio_item: Option<Box<AudioItem>>,\n    volume: u16,\n    shuffle: bool,\n    repeat: RepeatState,\n    play_request_id: Option<u64>,\n}\n\nfn insert_attr(map: &mut DbusMap, attr: impl ToString, value: impl RefArg + 'static) {\n    map.insert(attr.to_string(), Variant(Box::new(value)));\n}\n\nimpl CurrentStateInner {\n    fn mpris_volume(&self) -> f64 {\n        self.volume as f64 / u16::MAX as f64\n    }\n\n    fn get_position(&self) -> Option<Duration> {\n        let position = self.position.as_ref()?;\n        match self.status {\n            PlaybackStatus::Playing => Some(position.get_position()),\n            PlaybackStatus::Paused => Some(position.last_position),\n            PlaybackStatus::Stopped => None,\n        }\n    }\n\n    fn update_position(&mut self, position: Duration) {\n        self.position\n            .get_or_insert_with(Position::new)\n            .update_position(position);\n    }\n\n    fn handle_event(&mut self, event: PlayerEvent) -> (DbusMap, bool) {\n        let mut changed = DbusMap::new();\n        let mut seeked = false;\n\n        // note that get_play_request_id is None on PlayRequestIdChanged\n        if Option::zip(self.play_request_id, event.get_play_request_id())\n            .is_some_and(|(cur_id, event_id)| cur_id != event_id)\n        {\n            debug!(\"discarding event due to play_request_id mismatch\");\n            return (changed, seeked);\n        }\n\n        debug!(\"handling event {event:?}\");\n        match event {\n            PlayerEvent::VolumeChanged { volume } => {\n                self.volume = volume;\n                insert_attr(&mut changed, \"Volume\", self.mpris_volume());\n            }\n            PlayerEvent::Stopped { .. } => {\n                self.status = PlaybackStatus::Stopped;\n                self.audio_item = None;\n                insert_attr(\n                    &mut changed,\n                    \"PlaybackStatus\",\n                    self.status.to_mpris().to_string(),\n                );\n                insert_attr(&mut changed, \"Metadata\", self.to_metadata());\n            }\n            PlayerEvent::Playing { position_ms, .. } => {\n                if self.status != PlaybackStatus::Playing {\n                    self.status = PlaybackStatus::Playing;\n                    insert_attr(\n                        &mut changed,\n                        \"PlaybackStatus\",\n                        self.status.to_mpris().to_string(),\n                    );\n                }\n                self.update_position(Duration::milliseconds(position_ms as i64));\n                seeked = true;\n            }\n            PlayerEvent::Paused { position_ms, .. } => {\n                if self.status != PlaybackStatus::Paused {\n                    self.status = PlaybackStatus::Paused;\n                    insert_attr(\n                        &mut changed,\n                        \"PlaybackStatus\",\n                        self.status.to_mpris().to_string(),\n                    )\n                }\n                self.update_position(Duration::milliseconds(position_ms as i64));\n                seeked = true;\n            }\n            PlayerEvent::TrackChanged { audio_item } => {\n                self.audio_item = Some(audio_item);\n                insert_attr(&mut changed, \"Metadata\", self.to_metadata());\n            }\n            PlayerEvent::PositionCorrection { position_ms, .. }\n            | PlayerEvent::PositionChanged { position_ms, .. }\n            | PlayerEvent::Seeked { position_ms, .. } => {\n                self.update_position(Duration::milliseconds(position_ms as i64));\n                seeked = true;\n            }\n            PlayerEvent::ShuffleChanged { shuffle } => {\n                self.shuffle = shuffle;\n                insert_attr(&mut changed, \"Shuffle\", self.shuffle);\n            }\n            PlayerEvent::RepeatChanged { context, track } => {\n                self.repeat = (context, track).into();\n                insert_attr(\n                    &mut changed,\n                    \"LoopStatus\",\n                    self.repeat.to_mpris().to_string(),\n                )\n            }\n            PlayerEvent::PlayRequestIdChanged { play_request_id } => {\n                self.play_request_id = Some(play_request_id);\n            }\n            PlayerEvent::Preloading { .. }\n            | PlayerEvent::Loading { .. }\n            | PlayerEvent::TimeToPreloadNextTrack { .. }\n            | PlayerEvent::EndOfTrack { .. }\n            | PlayerEvent::Unavailable { .. }\n            | PlayerEvent::AutoPlayChanged { .. }\n            | PlayerEvent::FilterExplicitContentChanged { .. }\n            | PlayerEvent::SessionConnected { .. }\n            | PlayerEvent::SessionDisconnected { .. }\n            | PlayerEvent::SessionClientChanged { .. } => (),\n        }\n\n        (changed, seeked)\n    }\n\n    fn to_metadata(&self) -> DbusMap {\n        let mut m = HashMap::new();\n\n        insert_attr(\n            &mut m,\n            \"mpris:trackid\",\n            uri_to_object_path(\n                self.audio_item\n                    .as_deref()\n                    .and_then(|item| item.track_id.to_uri().ok())\n                    .as_deref(),\n            ),\n        );\n\n        if let Some(audio_item) = self.audio_item.as_deref() {\n            if let Some(length) =\n                Duration::milliseconds(audio_item.duration_ms as i64).num_microseconds()\n            {\n                insert_attr(&mut m, \"mpris:length\", length);\n            }\n\n            if let Some(cover) = audio_item.covers.iter().max_by_key(|im| im.width) {\n                insert_attr(&mut m, \"mpris:artUrl\", cover.url.clone());\n            }\n\n            insert_attr(&mut m, \"xesam:title\", audio_item.name.clone());\n\n            use librespot_metadata::audio::UniqueFields::*;\n            match &audio_item.unique_fields {\n                Local {\n                    artists,\n                    album,\n                    album_artists,\n                    number,\n                    disc_number,\n                    path,\n                } => {\n                    if let Some(artists) = artists {\n                        insert_attr(&mut m, \"xesam:artist\", artists.clone());\n                    }\n                    if let Some(album) = album {\n                        insert_attr(&mut m, \"xesam:album\", album.clone());\n                    }\n                    if let Some(album_artists) = album_artists {\n                        insert_attr(&mut m, \"xesam:albumArtist\", album_artists.clone());\n                    }\n                    if let Some(number) = number {\n                        insert_attr(&mut m, \"xesam:trackNumber\", *number);\n                    }\n                    if let Some(disc_number) = disc_number {\n                        insert_attr(&mut m, \"xesam:discNumber\", *disc_number);\n                    }\n                    insert_attr(&mut m, \"xesam:url\", format!(\"file://{:?}\", path));\n                }\n                Track {\n                    artists,\n                    album,\n                    album_artists,\n                    popularity,\n                    number,\n                    disc_number,\n                } => {\n                    insert_attr(\n                        &mut m,\n                        \"xesam:artist\",\n                        artists\n                            .iter()\n                            .map(|artist| artist.name.clone())\n                            .collect::<Vec<String>>(),\n                    );\n                    insert_attr(&mut m, \"xesam:album\", album.clone());\n                    insert_attr(&mut m, \"xesam:albumArtist\", album_artists.clone());\n                    insert_attr(&mut m, \"xesam:autoRating\", (*popularity as f64) / 100.0);\n                    insert_attr(&mut m, \"xesam:trackNumber\", *number);\n                    insert_attr(&mut m, \"xesam:discNumber\", *disc_number);\n                }\n                Episode {\n                    description,\n                    publish_time,\n                    show_name,\n                } => {\n                    insert_attr(&mut m, \"xesam:artist\", vec![show_name.clone()]);\n                    insert_attr(&mut m, \"xesam:comment\", vec![description.clone()]);\n                    if let Ok(formatted_publish) = publish_time.format(&Iso8601::DEFAULT) {\n                        insert_attr(&mut m, \"xesam:contentCreated\", formatted_publish);\n                    }\n                }\n            }\n        }\n\n        m\n    }\n}\n\n#[derive(Debug)]\nstruct CurrentState(RwLock<CurrentStateInner>);\n\n#[derive(Clone, Copy, Debug, Error)]\n#[error(\"internal state no longer available due to application error\")]\nstruct StatePoisonError;\n\nimpl From<StatePoisonError> for MethodErr {\n    fn from(value: StatePoisonError) -> Self {\n        MethodErr::failed(&value)\n    }\n}\n\nimpl CurrentState {\n    fn new(inner: CurrentStateInner) -> Self {\n        Self(RwLock::new(inner))\n    }\n\n    fn read(&self) -> Result<std::sync::RwLockReadGuard<'_, CurrentStateInner>, StatePoisonError> {\n        self.0.read().map_err(|_| StatePoisonError)\n    }\n\n    fn write(\n        &self,\n    ) -> Result<std::sync::RwLockWriteGuard<'_, CurrentStateInner>, StatePoisonError> {\n        self.0.write().map_err(|_| StatePoisonError)\n    }\n}\n\nasync fn create_dbus_server(\n    mut event_rx: UnboundedReceiver<PlayerEvent>,\n    mut control_rx: UnboundedReceiver<ControlMessage>,\n    dbus_type: DBusType,\n) -> Result<(), DbusError> {\n    let (resource, conn) = match dbus_type {\n        DBusType::Session => connection::new_session_sync(),\n        DBusType::System => connection::new_system_sync(),\n    }?;\n    let mut connection_task = tokio::spawn(async { Err::<(), _>(resource.await) });\n\n    // this name will be used, once we can provide the mpris interface\n    let mpris_name = format!(\n        \"org.mpris.MediaPlayer2.spotifyd.instance{}\",\n        std::process::id()\n    );\n    // this name will always be available to allow easy discovery of the controls interface\n    let spotifyd_name = format!(\"rs.spotifyd.instance{}\", std::process::id());\n\n    conn.request_name(&spotifyd_name, false, true, true).await?;\n\n    let mut cr = Crossroads::new();\n    cr.set_async_support(Some((\n        conn.clone(),\n        Box::new(|x| {\n            tokio::spawn(x);\n        }),\n    )));\n\n    let current_state = Arc::new(CurrentState::new(CurrentStateInner {\n        status: PlaybackStatus::Stopped,\n        position: None,\n        audio_item: None,\n        volume: u16::MAX,\n        shuffle: false,\n        repeat: RepeatState::None,\n        play_request_id: None,\n    }));\n\n    let (quit_tx, mut quit_rx) = tokio::sync::mpsc::unbounded_channel();\n\n    let cr = Arc::new(Mutex::new(cr));\n\n    let crossroads = cr.clone();\n    conn.start_receive(\n        MatchRule::new_method_call(),\n        Box::new(move |msg, conn| {\n            tokio::task::block_in_place(|| {\n                let mut cr = cr.blocking_lock();\n                cr.handle_message(msg, conn).unwrap();\n            });\n            true\n        }),\n    );\n\n    let mut spirc: Option<Arc<Spirc>> = None;\n    let mut session: Option<Session> = None;\n\n    struct ConnectionData {\n        conn_id: String,\n        seeked_fn: SeekedSignal,\n    }\n    let mut cur_conn: Option<ConnectionData> = None;\n\n    loop {\n        tokio::select! {\n            _ = quit_rx.recv() => {\n                break;\n            }\n            result = &mut connection_task => {\n                result.expect(\"the dbus connection panicked\")?;\n                break;\n            }\n            event = event_rx.recv() => {\n                let event = event.expect(\"event channel was unexpectedly closed\");\n\n                if let PlayerEvent::SessionConnected { connection_id, .. } = event {\n                    let mut cr = crossroads.lock().await;\n                    let seeked_fn = register_player_interface(\n                        &mut cr,\n                        spirc.clone().unwrap(),\n                        session.clone().unwrap(),\n                        current_state.clone(),\n                        quit_tx.clone(),\n                    );\n                    if cur_conn.is_none() {\n                        conn.request_name(&mpris_name, true, true, true).await?;\n                    }\n                    cur_conn = Some(ConnectionData { conn_id: connection_id, seeked_fn });\n                } else if let PlayerEvent::SessionDisconnected { connection_id, .. } = event {\n                    // if this message isn't outdated yet, we vanish from the bus\n                    if cur_conn.as_ref().is_some_and(|d| d.conn_id == connection_id) {\n                        let mut cr = crossroads.lock().await;\n                        conn.release_name(&mpris_name).await?;\n                        cr.remove::<()>(&MPRIS_PATH.into());\n                        cur_conn = None;\n                    }\n                } else {\n                    let (changed, seeked) = current_state\n                        .write()\n                        .expect(\"state has been poisoned\")\n                        .handle_event(event);\n\n                    if seeked {\n                        let position = current_state\n                            .read()\n                            .expect(\"state has been poisoned\")\n                            .get_position();\n                        if let Some((ConnectionData { seeked_fn, .. }, position)) =\n                            Option::zip(cur_conn.as_ref(), position)\n                        {\n                            let msg = seeked_fn(\n                                &MPRIS_PATH.into(),\n                                &(position.num_microseconds().unwrap_or_default(),),\n                            );\n                            conn.send(msg).unwrap();\n                        }\n                    }\n\n                    if !changed.is_empty() {\n                        let msg = PropertiesPropertiesChanged {\n                            interface_name: \"org.mpris.MediaPlayer2.Player\".to_owned(),\n                            changed_properties: changed,\n                            invalidated_properties: Vec::new(),\n                        };\n                        conn.send(\n                            msg.to_emit_message(&dbus::Path::new(MPRIS_PATH).unwrap()),\n                        )\n                        .unwrap();\n                    }\n                }\n\n            }\n            control = control_rx.recv() => {\n                let control = control.expect(\"control channel was unexpectedly closed\");\n                match control {\n                    ControlMessage::Shutdown => {\n                        break;\n                    },\n                    ControlMessage::SetSession(new_spirc, new_session) => {\n                        let mut cr = crossroads.lock().await;\n                        register_controls_interface(&mut cr, new_spirc.clone());\n                        spirc = Some(new_spirc);\n                        session = Some(new_session);\n                    }\n                    ControlMessage::DropSession => {\n                        let mut cr = crossroads.lock().await;\n                        conn.release_name(&mpris_name).await?;\n                        cr.remove::<()>(&MPRIS_PATH.into());\n                        cr.remove::<()>(&CONTROLS_PATH.into());\n                        spirc = None;\n                        session = None;\n                        cur_conn = None;\n                    }\n                }\n            }\n        }\n    }\n    conn.release_name(&mpris_name).await?;\n    conn.release_name(&spotifyd_name).await?;\n    Ok(())\n}\n\ntype SeekedSignal = Box<dyn Fn(&dbus::Path, &(i64,)) -> dbus::Message + Send + Sync + 'static>;\n\nfn register_player_interface(\n    cr: &mut Crossroads,\n    spirc: Arc<Spirc>,\n    session: Session,\n    current_state: Arc<CurrentState>,\n    quit_tx: tokio::sync::mpsc::UnboundedSender<()>,\n) -> SeekedSignal {\n    // The following methods and properties are part of the MediaPlayer2 interface.\n    // https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html\n    let media_player2_interface = cr.register(\"org.mpris.MediaPlayer2\", move |b| {\n        let mut quit_tx = Some(quit_tx);\n        b.method(\"Raise\", (), (), move |_, _, (): ()| {\n            // noop\n            Ok(())\n        });\n        b.method(\"Quit\", (), (), move |_, _, (): ()| {\n            quit_tx.take().unwrap().send(()).ok();\n            Ok(())\n        });\n        b.property(\"CanQuit\")\n            .emits_changed_const()\n            .get(|_, _| Ok(true));\n        b.property(\"CanRaise\")\n            .emits_changed_const()\n            .get(|_, _| Ok(false));\n        b.property(\"CanSetFullscreen\")\n            .emits_changed_const()\n            .get(|_, _| Ok(false));\n        b.property(\"HasTrackList\")\n            .emits_changed_const()\n            .get(|_, _| Ok(false));\n        b.property(\"Identity\")\n            .emits_changed_const()\n            .get(|_, _| Ok(\"Spotifyd\".to_string()));\n        b.property(\"SupportedUriSchemes\")\n            .emits_changed_const()\n            .get(|_, _| Ok(vec![\"spotify\".to_string()]));\n        b.property(\"SupportedMimeTypes\")\n            .emits_changed_const()\n            .get(|_, _| Ok(Vec::<String>::new()));\n    });\n\n    // The following methods and properties are part of the MediaPlayer2.Player interface.\n    // https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html\n\n    let mut seeked_signal = None;\n\n    let player_interface: IfaceToken<()> = cr.register(\"org.mpris.MediaPlayer2.Player\", |b| {\n        seeked_signal = Some(b.signal::<(i64,), _>(\"Seeked\", (\"Position\",)).msg_fn());\n        let local_spirc = spirc.clone();\n        b.method(\"VolumeUp\", (), (), move |_, _, (): ()| {\n            local_spirc.volume_up().map_err(|e| MethodErr::failed(&e))\n        })\n        .deprecated();\n        let local_spirc = spirc.clone();\n        b.method(\"VolumeDown\", (), (), move |_, _, (): ()| {\n            local_spirc.volume_down().map_err(|e| MethodErr::failed(&e))\n        })\n        .deprecated();\n        let local_spirc = spirc.clone();\n        b.method(\"Next\", (), (), move |_, _, (): ()| {\n            local_spirc.next().map_err(|e| MethodErr::failed(&e))\n        });\n        let local_spirc = spirc.clone();\n        b.method(\"Previous\", (), (), move |_, _, (): ()| {\n            local_spirc.prev().map_err(|e| MethodErr::failed(&e))\n        });\n        let local_spirc = spirc.clone();\n        b.method(\"Pause\", (), (), move |_, _, (): ()| {\n            local_spirc.pause().map_err(|e| MethodErr::failed(&e))\n        });\n        let local_spirc = spirc.clone();\n        b.method(\"PlayPause\", (), (), move |_, _, (): ()| {\n            warn!(\"PlayPause method called via mpris\");\n            local_spirc.play_pause().map_err(|e| MethodErr::failed(&e))\n        });\n        let local_spirc = spirc.clone();\n        b.method(\"Play\", (), (), move |_, _, (): ()| {\n            warn!(\"Play method called via mpris\");\n            local_spirc.play().map_err(|e| MethodErr::failed(&e))\n        });\n        let local_spirc = spirc.clone();\n        b.method(\"Stop\", (), (), move |_, _, (): ()| {\n            let pause_playback = false;\n            local_spirc\n                .disconnect(pause_playback)\n                .map_err(|e| MethodErr::failed(&e))\n        });\n\n        let local_spirc = spirc.clone();\n        let local_state = current_state.clone();\n        b.method(\"Seek\", (\"offset\",), (), move |_, _, (offset,): (i64,)| {\n            let Some(position) = local_state.read()?.get_position() else {\n                return Err(dbus::MethodErr::failed(\n                    \"cannot seek while playback is stopped\",\n                ));\n            };\n            let new_pos = position + Duration::microseconds(offset);\n            let new_pos_ms = u32::try_from(new_pos.num_milliseconds()).map_err(|err| {\n                dbus::MethodErr::invalid_arg(&format!(\"new position out of bounds: {err}\"))\n            })?;\n            if let Err(err) = local_spirc.set_position_ms(new_pos_ms) {\n                warn!(\"failed to seek by {offset}ms: {err}\");\n                return Err(dbus::MethodErr::failed(&err));\n            }\n            Ok(())\n        });\n\n        let local_spirc = spirc.clone();\n        let local_state = current_state.clone();\n        b.method(\n            \"SetPosition\",\n            (\"track_id\", \"position\"),\n            (),\n            move |_, _, (track_id, pos): (dbus::Path, i64)| {\n                let Some((current_track_id, duration)) = local_state\n                    .read()?\n                    .audio_item\n                    .as_ref()\n                    .map(|item| (item.track_id.clone(), item.duration_ms))\n                else {\n                    return Err(dbus::MethodErr::failed(\n                        \"can set position while nothing is playing\",\n                    ));\n                };\n                let duration = Duration::milliseconds(duration.into());\n\n                if !track_id.ends_with(&current_track_id.to_id().unwrap()) {\n                    // as per mpris spec: ignore as stale\n                    return Ok(());\n                }\n                let new_position = Duration::microseconds(pos);\n                if new_position < Duration::zero() || new_position > duration {\n                    // ignore as per spec\n                    return Ok(());\n                }\n                if let Err(err) =\n                    local_spirc.set_position_ms(new_position.num_milliseconds() as u32)\n                {\n                    return Err(dbus::MethodErr::failed(&err));\n                }\n\n                Ok(())\n            },\n        );\n\n        let local_spirc = spirc.clone();\n        let local_state = current_state.clone();\n        b.method(\"OpenUri\", (\"uri\",), (), move |_, _, (uri,): (String,)| {\n            let uri = SpotifyUri::from_uri(uri.as_str()).map_err(|e| MethodErr::invalid_arg(&e))?;\n            let CurrentStateInner {\n                shuffle, repeat, ..\n            } = *local_state.read()?;\n\n            let session = session.clone();\n\n            let (playing_track_index, context_uri) = Handle::current()\n                .block_on(async move {\n                    use librespot_metadata::*;\n                    Ok::<_, librespot_core::Error>(match uri {\n                        SpotifyUri::Track { .. } => {\n                            let track = Track::get(&session, &uri).await?;\n                            if track.number == 0 {\n                                warn!(\"track.number is not expected to be 0- but 1-indexed\");\n                            }\n                            ((track.number - 1).max(0) as u32, track.album.id.to_uri()?)\n                        }\n                        SpotifyUri::Album { .. }\n                        | SpotifyUri::Artist { .. }\n                        | SpotifyUri::Playlist { .. }\n                        | SpotifyUri::Episode { .. }\n                        | SpotifyUri::Show { .. } => (0, uri.to_uri()?),\n                        SpotifyUri::Local { .. } | SpotifyUri::Unknown { .. } => {\n                            return Err(librespot_core::Error::unimplemented(\n                                \"this type of uri is not supported\",\n                            ));\n                        }\n                    })\n                })\n                .map_err(|e| MethodErr::failed(&e))?;\n\n            warn!(\n                \"loading context_uri {context_uri} with playing_track_index {playing_track_index}\"\n            );\n            local_spirc\n                .load(LoadRequest::from_context_uri(\n                    context_uri,\n                    LoadRequestOptions {\n                        start_playing: true,\n                        seek_to: 0,\n                        context_options: Some(LoadContextOptions::Options(\n                            librespot_connect::Options {\n                                shuffle,\n                                repeat: repeat.repeat_context(),\n                                repeat_track: repeat.repeat_track(),\n                            },\n                        )),\n                        playing_track: Some(librespot_connect::PlayingTrack::Index(\n                            playing_track_index,\n                        )),\n                    },\n                ))\n                .map_err(|e| MethodErr::failed(&e))\n        });\n\n        let local_state = current_state.clone();\n        b.property(\"PlaybackStatus\")\n            .emits_changed_false()\n            .get(move |_, _| {\n                let playback_state = local_state.read()?.status;\n                Ok(playback_state.to_mpris().to_string())\n            });\n\n        let local_spirc = spirc.clone();\n        let local_state = current_state.clone();\n        b.property(\"Shuffle\")\n            .emits_changed_false()\n            .get(move |_, _| Ok(local_state.read()?.shuffle))\n            .set(move |_, _, value| {\n                local_spirc\n                    .shuffle(value)\n                    .map(|_| None)\n                    .map_err(|err| dbus::MethodErr::failed(&err))\n            });\n\n        b.property(\"Rate\").emits_changed_const().get(|_, _| Ok(1.0));\n        b.property(\"MaximumRate\")\n            .emits_changed_const()\n            .get(|_, _| Ok(1.0));\n        b.property(\"MinimumRate\")\n            .emits_changed_const()\n            .get(|_, _| Ok(1.0));\n\n        let local_spirc = spirc.clone();\n        let local_state = current_state.clone();\n        b.property(\"Volume\")\n            .emits_changed_false()\n            .get(move |_, _| Ok(local_state.read()?.mpris_volume()))\n            .set(move |_, _, value| {\n                if let Err(err) = local_spirc.set_volume((value * u16::MAX as f64) as u16) {\n                    return Err(dbus::MethodErr::failed(&err));\n                }\n                Ok(None)\n            });\n\n        let local_spirc = spirc.clone();\n        let local_state = current_state.clone();\n        b.property(\"LoopStatus\")\n            .emits_changed_true()\n            .get(move |_, _| {\n                let repeat = local_state.read()?.repeat;\n                Ok(repeat.to_mpris().to_string())\n            })\n            .set(move |_, _, value| {\n                let repeat = match value.as_str() {\n                    \"None\" => RepeatState::None,\n                    \"Playlist\" => RepeatState::All,\n                    \"Track\" => RepeatState::Track,\n                    mode => {\n                        return Err(dbus::MethodErr::failed(&format!(\n                            \"unsupported repeat mode: {mode}\"\n                        )));\n                    }\n                };\n\n                local_spirc\n                    .repeat(repeat.repeat_context())\n                    .map_err(|e| MethodErr::failed(&e))?;\n                local_spirc\n                    .repeat_track(repeat.repeat_track())\n                    .map_err(|e| MethodErr::failed(&e))?;\n\n                Ok(None)\n            });\n\n        let local_state = current_state.clone();\n        b.property(\"Position\")\n            .emits_changed_false()\n            .get(move |_, _| {\n                let Some(position) = local_state.read()?.get_position() else {\n                    return Err(dbus::MethodErr::failed(\"no position available currently\"));\n                };\n\n                Ok(position.num_microseconds().unwrap_or_default())\n            });\n\n        let local_state = current_state.clone();\n        b.property(\"Metadata\")\n            .emits_changed_false()\n            .get(move |_, _| Ok(local_state.read()?.to_metadata()));\n\n        for prop in [\n            \"CanPlay\",\n            \"CanPause\",\n            \"CanSeek\",\n            \"CanControl\",\n            \"CanGoPrevious\",\n            \"CanGoNext\",\n        ] {\n            b.property(prop).emits_changed_const().get(|_, _| Ok(true));\n        }\n    });\n\n    cr.insert(MPRIS_PATH, &[media_player2_interface, player_interface], ());\n\n    seeked_signal.expect(\"player interface has not been registered\")\n}\n\nfn register_controls_interface(cr: &mut Crossroads, spirc: Arc<Spirc>) {\n    let spotifyd_ctrls_interface: IfaceToken<()> = cr.register(\"rs.spotifyd.Controls\", |b| {\n        let local_spirc = spirc.clone();\n        b.method(\"VolumeUp\", (), (), move |_, _, (): ()| {\n            local_spirc.volume_up().map_err(|e| MethodErr::failed(&e))\n        });\n        let local_spirc = spirc.clone();\n        b.method(\"VolumeDown\", (), (), move |_, _, (): ()| {\n            local_spirc.volume_down().map_err(|e| MethodErr::failed(&e))\n        });\n\n        let local_spirc = spirc.clone();\n        b.method(\"TransferPlayback\", (), (), move |_, _, (): ()| {\n            local_spirc.activate().map_err(|e| MethodErr::failed(&e))\n        });\n    });\n\n    cr.insert(CONTROLS_PATH, &[spotifyd_ctrls_interface], ());\n}\n\nfn uri_to_object_path(uri: Option<&str>) -> dbus::Path<'static> {\n    let Some(uri) = uri else {\n        return dbus::Path::new(\"/org/mpris/MediaPlayer2/TrackList/NoTrack\").unwrap();\n    };\n    let mut path = String::with_capacity(uri.len() + 1);\n    for element in uri.split(':') {\n        path.push('/');\n        path.push_str(element);\n    }\n    dbus::Path::new(path).unwrap()\n}\n"
  },
  {
    "path": "src/error.rs",
    "content": "use std::fmt::{self, Display};\n\n/// This crate's error type.\n#[derive(Debug)]\npub(crate) struct Error {\n    kind: ErrorKind,\n}\n\nimpl Error {\n    pub(crate) fn subprocess(shell: &str, cmd: &str) -> Self {\n        Self {\n            kind: ErrorKind::Subprocess {\n                cmd: cmd.into(),\n                msg: Message::None,\n                shell: shell.into(),\n            },\n        }\n    }\n\n    pub(crate) fn subprocess_with_err<E>(shell: &str, cmd: &str, e: E) -> Self\n    where\n        E: std::error::Error + 'static,\n    {\n        Self {\n            kind: ErrorKind::Subprocess {\n                cmd: cmd.into(),\n                msg: Message::Error(Box::new(e)),\n                shell: shell.into(),\n            },\n        }\n    }\n\n    pub(crate) fn subprocess_with_str(shell: &str, cmd: &str, s: &str) -> Self {\n        Self {\n            kind: ErrorKind::Subprocess {\n                cmd: cmd.into(),\n                msg: Message::String(s.into()),\n                shell: shell.into(),\n            },\n        }\n    }\n}\n\nimpl From<ErrorKind> for Error {\n    fn from(kind: ErrorKind) -> Self {\n        Self { kind }\n    }\n}\n\nimpl Display for Error {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        write!(f, \"{}\", self.kind)\n    }\n}\n\nimpl std::error::Error for Error {}\n\n/// This crate's error kind type.\n#[derive(Debug)]\npub(crate) enum ErrorKind {\n    Subprocess {\n        cmd: String,\n        msg: Message,\n        shell: String,\n    },\n    #[allow(unused)]\n    NormalisationPregainInvalid,\n}\n\nimpl Display for ErrorKind {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        match self {\n            ErrorKind::Subprocess { cmd, msg, shell } => match msg {\n                Message::None => write!(f, \"Failed to execute {cmd} using {shell}.\"),\n                Message::Error(e) => {\n                    write!(f, \"Failed to execute {cmd} using {shell}. Error: {e}\",)\n                }\n                Message::String(s) => {\n                    write!(f, \"Failed to execute {cmd} using {shell}. Error: {s}\",)\n                }\n            },\n            ErrorKind::NormalisationPregainInvalid => write!(\n                f,\n                \"normalisation-pregain must be a valid 32-bit floating point number.\"\n            ),\n        }\n    }\n}\n\n#[derive(Debug)]\npub(crate) enum Message {\n    None,\n    String(String),\n    Error(Box<dyn std::error::Error + 'static>),\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "use crate::config::CliConfig;\nuse clap::Parser;\n#[cfg(unix)]\nuse color_eyre::eyre::eyre;\nuse color_eyre::eyre::{self, Context};\nuse config::ExecutionMode;\n#[cfg(unix)]\nuse daemonize::Daemonize;\nuse fern::colors::ColoredLevelConfig;\nuse log::{LevelFilter, info, trace};\nuse oauth::run_oauth;\n#[cfg(target_os = \"openbsd\")]\nuse pledge::pledge;\n#[cfg(windows)]\nuse std::fs;\nuse tokio::runtime::Runtime;\n\n#[cfg(feature = \"alsa_backend\")]\nmod alsa_mixer;\nmod config;\n#[cfg(feature = \"dbus_mpris\")]\nmod dbus_mpris;\nmod error;\nmod main_loop;\nmod no_mixer;\nmod oauth;\nmod process;\nmod setup;\nmod utils;\n\nenum LogTarget {\n    Terminal,\n    Syslog,\n}\n\nfn setup_logger(log_target: LogTarget, verbose: u8) -> eyre::Result<()> {\n    let log_level = match verbose {\n        0 => LevelFilter::Info,\n        1 => LevelFilter::Debug,\n        2.. => LevelFilter::Trace,\n    };\n\n    let mut logger = fern::Dispatch::new().level(log_level);\n\n    if verbose == 0 {\n        logger = logger.level_for(\"symphonia_format_ogg::demuxer\", LevelFilter::Warn);\n    }\n\n    let logger = match log_target {\n        LogTarget::Terminal => {\n            let colors = ColoredLevelConfig::new();\n            logger\n                .format(move |out, message, record| {\n                    let target = if verbose > 0 {\n                        &format!(\" {}\", record.target())\n                    } else {\n                        \"\"\n                    };\n                    out.finish(format_args!(\n                        \"[{}{}] {}\",\n                        colors.color(record.level()),\n                        target,\n                        message\n                    ))\n                })\n                .chain(std::io::stdout())\n        }\n        #[cfg(unix)]\n        LogTarget::Syslog => {\n            let log_format = syslog::Formatter3164 {\n                facility: syslog::Facility::LOG_DAEMON,\n                hostname: None,\n                process: \"spotifyd\".to_owned(),\n                pid: std::process::id(),\n            };\n            logger.chain(\n                syslog::unix(log_format)\n                    .map_err(|e| eyre!(\"Couldn't connect to syslog instance: {}\", e))?,\n            )\n        }\n        #[cfg(target_os = \"windows\")]\n        LogTarget::Syslog => {\n            let dirs = directories::BaseDirs::new().unwrap();\n            let mut log_file = dirs.data_local_dir().to_path_buf();\n            log_file.push(\"spotifyd\");\n            log_file.push(\".spotifyd.log\");\n\n            if let Some(p) = log_file.parent() {\n                fs::create_dir_all(p)?\n            };\n            logger.chain(\n                fs::OpenOptions::new()\n                    .write(true)\n                    .create(true)\n                    .truncate(true)\n                    .open(log_file)\n                    .expect(\"Couldn't initialize logger\"),\n            )\n        }\n    };\n\n    logger.apply().wrap_err(\"Couldn't initialize logger\")\n}\n\nfn main() -> eyre::Result<()> {\n    // Start with superset of all potentially required promises.\n    // Drop later after CLI arguments and configuration files were parsed.\n    #[cfg(target_os = \"openbsd\")]\n    pledge(\n        \"stdio rpath wpath cpath inet mcast flock chown unix dns proc exec audio\",\n        None,\n    )\n    .unwrap();\n\n    color_eyre::install().wrap_err(\"Couldn't initialize error reporting\")?;\n\n    let cli_config = CliConfig::parse();\n\n    match cli_config.mode {\n        None => run_daemon(cli_config),\n        Some(ExecutionMode::Authenticate { oauth_port }) => run_oauth(cli_config, oauth_port),\n    }\n}\n\nfn run_daemon(mut cli_config: CliConfig) -> eyre::Result<()> {\n    let is_daemon = !cli_config.no_daemon;\n\n    let log_target = if is_daemon {\n        #[cfg(unix)]\n        {\n            LogTarget::Syslog\n        }\n        #[cfg(target_os = \"windows\")]\n        {\n            LogTarget::Terminal\n        }\n    } else {\n        #[cfg(unix)]\n        {\n            LogTarget::Terminal\n        }\n        #[cfg(target_os = \"windows\")]\n        {\n            if std::env::var(\"SPOTIFYD_CHILD\").is_ok() {\n                LogTarget::Syslog\n            } else {\n                LogTarget::Terminal\n            }\n        }\n    };\n\n    setup_logger(log_target, cli_config.verbose)?;\n\n    cli_config\n        .load_config_file_values()\n        .wrap_err(\"could not load the config file\")?;\n    trace!(\"{:?}\", &cli_config);\n\n    // Returns the old SpotifydConfig struct used within the rest of the daemon.\n    let internal_config = config::get_internal_config(cli_config);\n\n    if is_daemon {\n        info!(\"Daemonizing running instance\");\n\n        #[cfg(unix)]\n        {\n            let mut daemonize = Daemonize::new();\n            if let Some(pid) = internal_config.pid.as_ref() {\n                daemonize = daemonize.pid_file(pid);\n            }\n            match daemonize.start() {\n                Ok(_) => info!(\"Detached from shell, now running in background.\"),\n                Err(e) => return Err(e).wrap_err(\"something went wrong while daemonizing\"),\n            };\n        }\n        #[cfg(target_os = \"windows\")]\n        {\n            use std::os::windows::process::CommandExt;\n            use std::process::{Command, exit};\n\n            let mut args = std::env::args().collect::<Vec<_>>();\n            args.remove(0);\n            args.push(\"--no-daemon\".to_string());\n\n            Command::new(std::env::current_exe().unwrap())\n                .args(args)\n                .env(\"SPOTIFYD_CHILD\", \"1\")\n                .creation_flags(8 /* DETACHED_PROCESS */)\n                .spawn()\n                .expect(\"Couldn't spawn daemon\");\n\n            exit(0);\n        }\n    }\n\n    #[cfg(target_os = \"openbsd\")]\n    {\n        // At this point:\n        //   * --username-cmd, --password-cmd were handled\n        //     > no \"proc exec\"\n        //   * --pid, daemon(3) were handled\n        //     > no \"cpath flock chown\" for PID file\n        //     > no \"proc\" for double-fork(2)\n        //\n        // Required runtime promises:\n        // stdout/err, syslog(3)    \"stdio\"\n        // ${TMPDIR}/.tmp*, cache   \"[rwc]path\"\n        // Spotify API/Connect      \"inet dns\"\n        // D-Bus, MPRIS             \"unix\"\n        // Zeroconf Discovery       \"mcast\"\n        // PortAudio, sio_open(3)  (\"[rwc]path unix inet audio\")\n        // > after sndio(7) cookie  \"audio\"\n\n        // --on-song-change-hook aka. \"onevent\", run via --shell aka. \"shell\"\n        if internal_config.onevent.is_some() {\n            pledge(\n                \"stdio rpath wpath cpath inet mcast unix dns proc exec audio\",\n                None,\n            )\n            .unwrap();\n        } else {\n            pledge(\"stdio rpath wpath cpath inet mcast unix dns audio\", None).unwrap();\n        }\n    }\n\n    let runtime = Runtime::new().unwrap();\n    runtime.block_on(async {\n        let initial_state = setup::initial_state(internal_config)?;\n        initial_state.run().await\n    })\n}\n"
  },
  {
    "path": "src/main_loop.rs",
    "content": "#[cfg(feature = \"dbus_mpris\")]\nuse crate::config::{DBusType, MprisConfig};\n#[cfg(feature = \"dbus_mpris\")]\nuse crate::dbus_mpris::DbusServer;\nuse crate::process::spawn_program_on_event;\nuse crate::utils::Backoff;\nuse color_eyre::eyre::{self, Context};\nuse futures::future::Either;\n#[cfg(not(feature = \"dbus_mpris\"))]\nuse futures::future::Pending;\nuse futures::{\n    self, Future, FutureExt, StreamExt,\n    future::{self, Fuse, FusedFuture},\n    stream::Peekable,\n};\nuse librespot_connect::{ConnectConfig, Spirc};\nuse librespot_core::{\n    Error, SessionConfig, authentication::Credentials, cache::Cache, config::DeviceType,\n    session::Session,\n};\nuse librespot_discovery::Discovery;\nuse librespot_playback::{\n    audio_backend::Sink,\n    config::{AudioFormat, PlayerConfig},\n    mixer::Mixer,\n    player::Player,\n};\nuse log::{error, info};\nuse std::pin::Pin;\nuse std::sync::Arc;\n\n#[cfg(not(feature = \"dbus_mpris\"))]\ntype DbusServer = Pending<()>;\n\npub(crate) enum CredentialsProvider {\n    Discovery {\n        stream: Peekable<Discovery>,\n        last_credentials: Option<Credentials>,\n    },\n    CredentialsOnly(Credentials),\n}\n\nimpl CredentialsProvider {\n    async fn get_credentials(&mut self) -> Credentials {\n        match self {\n            CredentialsProvider::Discovery {\n                stream,\n                last_credentials,\n            } => {\n                let new_creds = match last_credentials.take() {\n                    Some(creds) => stream.next().now_or_never().flatten().unwrap_or(creds),\n                    None => stream.next().await.unwrap(),\n                };\n                *last_credentials = Some(new_creds.clone());\n                new_creds\n            }\n            CredentialsProvider::CredentialsOnly(creds) => creds.clone(),\n        }\n    }\n\n    // wait for an incoming connection if the underlying provider is a discovery stream\n    async fn incoming_connection(&mut self) {\n        match self {\n            CredentialsProvider::Discovery { stream, .. } => {\n                let peeked = Pin::new(stream).peek().await;\n                if peeked.is_none() {\n                    future::pending().await\n                }\n            }\n            _ => future::pending().await,\n        }\n    }\n}\n\npub(crate) struct MainLoop {\n    pub(crate) session_config: SessionConfig,\n    pub(crate) player_config: PlayerConfig,\n    pub(crate) cache: Option<Cache>,\n    pub(crate) mixer: Arc<dyn Mixer>,\n    pub(crate) backend: fn(Option<String>, AudioFormat) -> Box<dyn Sink>,\n    pub(crate) audio_device: Option<String>,\n    pub(crate) audio_format: AudioFormat,\n    pub(crate) disable_volume: bool,\n    pub(crate) initial_volume: u16,\n    pub(crate) shell: String,\n    pub(crate) device_type: DeviceType,\n    pub(crate) device_name: String,\n    pub(crate) player_event_program: Option<String>,\n    pub(crate) credentials_provider: CredentialsProvider,\n    #[cfg(feature = \"dbus_mpris\")]\n    pub(crate) mpris_config: MprisConfig,\n}\n\nstruct ConnectionInfo<SpircTask: Future<Output = ()>> {\n    spirc: Spirc,\n    #[cfg_attr(not(feature = \"dbus_mpris\"), expect(unused))]\n    session: Session,\n    player: Arc<Player>,\n    spirc_task: SpircTask,\n}\n\nimpl MainLoop {\n    async fn get_connection(\n        &mut self,\n    ) -> Result<ConnectionInfo<impl Future<Output = ()> + use<>>, Error> {\n        let creds = self.credentials_provider.get_credentials().await;\n\n        let mut connection_backoff = Backoff::default();\n        loop {\n            let session = Session::new(self.session_config.clone(), self.cache.clone());\n            let player = {\n                let audio_device = self.audio_device.clone();\n                let audio_format = self.audio_format;\n                let backend = self.backend;\n                Player::new(\n                    self.player_config.clone(),\n                    session.clone(),\n                    self.mixer.get_soft_volume(),\n                    move || backend(audio_device, audio_format),\n                )\n            };\n\n            // TODO: expose is_group\n            match Spirc::new(\n                ConnectConfig {\n                    name: self.device_name.clone(),\n                    device_type: self.device_type,\n                    initial_volume: self.initial_volume,\n                    disable_volume: self.disable_volume,\n                    ..ConnectConfig::default()\n                },\n                session.clone(),\n                creds.clone(),\n                player.clone(),\n                self.mixer.clone(),\n            )\n            .await\n            {\n                Ok((spirc, spirc_task)) => {\n                    break Ok(ConnectionInfo {\n                        spirc,\n                        session,\n                        player,\n                        spirc_task,\n                    });\n                }\n                Err(err) => {\n                    let Ok(backoff) = connection_backoff.next_backoff() else {\n                        break Err(err);\n                    };\n                    error!(\"connection to spotify failed: {err}\");\n                    info!(\n                        \"retrying connection in {} seconds (retry {}/{})\",\n                        backoff.as_secs(),\n                        connection_backoff.retries(),\n                        connection_backoff.max_retries()\n                    );\n                    tokio::time::sleep(backoff).await;\n                }\n            }\n        }\n    }\n\n    pub(crate) async fn run(mut self) -> eyre::Result<()> {\n        tokio::pin! {\n            let ctrl_c = tokio::signal::ctrl_c();\n            // we don't necessarily have a dbus server\n            let dbus_server = Either::<DbusServer, _>::Right(future::pending());\n        }\n\n        #[cfg(feature = \"dbus_mpris\")]\n        let mpris_event_tx = if self.mpris_config.use_mpris.unwrap_or(true) {\n            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();\n            *dbus_server.as_mut() = Either::Left(DbusServer::new(\n                rx,\n                self.mpris_config.dbus_type.unwrap_or(DBusType::Session),\n            ));\n            Some(tx)\n        } else {\n            None\n        };\n\n        let mainloop_result: eyre::Result<()> = 'mainloop: loop {\n            let connection = tokio::select!(\n                _ = &mut ctrl_c => {\n                    break 'mainloop Ok(());\n                }\n                connection = self.get_connection() => {\n                    match connection {\n                        Ok(connection) => connection,\n                        Err(err) => break 'mainloop Err(err).wrap_err(\"failed to connect to spotify\"),\n                    }\n                }\n            );\n\n            let spirc_task = connection.spirc_task;\n            tokio::pin!(spirc_task);\n\n            let shared_spirc = Arc::new(connection.spirc);\n\n            #[cfg(feature = \"dbus_mpris\")]\n            if let Either::Left(mut dbus_server) = Either::as_pin_mut(dbus_server.as_mut())\n                && let Err(err) = dbus_server\n                    .as_mut()\n                    .set_session(shared_spirc.clone(), connection.session)\n            {\n                let _ = shared_spirc.shutdown();\n                let _ = (&mut spirc_task).await;\n                break 'mainloop Err(err).wrap_err(\"failed to configure dbus server\");\n            }\n\n            let mut running_event_program = Box::pin(Fuse::terminated());\n\n            let mut event_channel = connection.player.get_player_event_channel();\n\n            loop {\n                tokio::select!(\n                    // a new session has been started via the discovery stream\n                    _ = self.credentials_provider.incoming_connection() => {\n                        let _ = shared_spirc.shutdown();\n                        let _ = (&mut spirc_task).await;\n                        break;\n                    }\n                    // the program should shut down\n                    _ = &mut ctrl_c => {\n                        let _ = shared_spirc.shutdown();\n                        let _ = (&mut spirc_task).await;\n                        break 'mainloop Ok(());\n                    }\n                    // spirc was shut down by some external factor\n                    _ = &mut spirc_task => {\n                        break;\n                    }\n                    // dbus stopped unexpectedly\n                    result = &mut dbus_server => {\n                        #[cfg(feature = \"dbus_mpris\")]\n                        {\n                            let _ = shared_spirc.shutdown();\n                            let _ = (&mut spirc_task).await;\n                            *dbus_server.as_mut() = Either::Right(future::pending());\n                            break 'mainloop result.wrap_err(\"DBus terminated unexpectedly\");\n                        }\n                        #[cfg(not(feature = \"dbus_mpris\"))]\n                        result // unused variable\n                    }\n                    // a new player event is available and no program is running\n                    event = event_channel.recv(), if running_event_program.is_terminated() => {\n                        let event = event.unwrap();\n                        #[cfg(feature = \"dbus_mpris\")]\n                        if let Some(ref tx) = mpris_event_tx {\n                            tx.send(event.clone()).unwrap();\n                        }\n                        if let Some(ref cmd) = self.player_event_program {\n                            match spawn_program_on_event(&self.shell, cmd, event) {\n                                Ok(child) => running_event_program = Box::pin(child.wait().fuse()),\n                                Err(e) => error!(\"{}\", e),\n                            }\n                        }\n                    }\n                    // a running program has finished\n                    result = &mut running_event_program, if !running_event_program.is_terminated() => {\n                        match result {\n                            // Exited without error...\n                            Ok(_) => (),\n                            // Exited with error...\n                            Err(e) => error!(\"{}\", e),\n                        }\n                    }\n                )\n            }\n            #[cfg(feature = \"dbus_mpris\")]\n            if let Either::Left(dbus_server) = Either::as_pin_mut(dbus_server.as_mut())\n                && let Err(err) = dbus_server.drop_session()\n            {\n                break 'mainloop Err(err).wrap_err(\"failed to reconfigure DBus server\");\n            }\n        };\n\n        if let CredentialsProvider::Discovery { stream, .. } = self.credentials_provider {\n            let _ = stream.into_inner().shutdown().await;\n        }\n        #[cfg(feature = \"dbus_mpris\")]\n        if let Either::Left(dbus_server) = Either::as_pin_mut(dbus_server.as_mut())\n            && dbus_server.shutdown()\n            && let Err(err) = dbus_server.await\n        {\n            let err = Err(err).wrap_err(\"failed to shutdown DBus server\");\n            if mainloop_result.is_ok() {\n                return err;\n            } else {\n                error!(\"additional error while shutting down: {err:?}\");\n            }\n        }\n        mainloop_result\n    }\n}\n"
  },
  {
    "path": "src/no_mixer.rs",
    "content": "use librespot_playback::mixer::{Mixer, MixerConfig};\n\npub struct NoMixer;\n\nimpl Mixer for NoMixer {\n    fn open(_: MixerConfig) -> Result<NoMixer, librespot_core::Error> {\n        Ok(NoMixer {})\n    }\n\n    fn volume(&self) -> u16 {\n        u16::MAX\n    }\n\n    fn set_volume(&self, _volume: u16) {}\n}\n"
  },
  {
    "path": "src/oauth.rs",
    "content": "use color_eyre::{\n    Section as _,\n    eyre::{self, Context as _},\n};\nuse librespot_core::SessionConfig;\nuse librespot_core::{Session, authentication::Credentials};\nuse librespot_oauth::OAuthClientBuilder;\nuse log::info;\nuse tokio::runtime::Runtime;\n\nuse crate::{LogTarget, config::CliConfig, setup_logger};\n\npub(crate) fn run_oauth(mut cli_config: CliConfig, oauth_port: u16) -> eyre::Result<()> {\n    setup_logger(LogTarget::Terminal, cli_config.verbose)?;\n\n    cli_config\n        .load_config_file_values()\n        .wrap_err(\"failed to read config file\")?;\n\n    let cache = cli_config\n        .shared_config\n        .get_cache(true)\n        .with_note(|| \"The result of the authentication needs to be cached to be usable later.\")?;\n\n    const OAUTH_SCOPES: &[&str] = &[\n        \"app-remote-control\",\n        \"playlist-modify\",\n        \"playlist-modify-private\",\n        \"playlist-modify-public\",\n        \"playlist-read\",\n        \"playlist-read-collaborative\",\n        \"playlist-read-private\",\n        \"streaming\",\n        \"ugc-image-upload\",\n        \"user-follow-modify\",\n        \"user-follow-read\",\n        \"user-library-modify\",\n        \"user-library-read\",\n        \"user-modify\",\n        \"user-modify-playback-state\",\n        \"user-modify-private\",\n        \"user-personalized\",\n        \"user-read-birthdate\",\n        \"user-read-currently-playing\",\n        \"user-read-email\",\n        \"user-read-play-history\",\n        \"user-read-playback-position\",\n        \"user-read-playback-state\",\n        \"user-read-private\",\n        \"user-read-recently-played\",\n        \"user-top-read\",\n    ];\n\n    let session_config = SessionConfig {\n        proxy: cli_config.shared_config.proxy_url(),\n        ..Default::default()\n    };\n\n    let oauth_client = OAuthClientBuilder::new(\n        &session_config.client_id,\n        &format!(\"http://127.0.0.1:{oauth_port}/login\"),\n        OAUTH_SCOPES.to_vec(),\n    )\n    .with_custom_message(r#\"<h3 style=\"color: darkgreen; align: center;\">Authentication successful! You can now return to spotifyd.</h3>\"#)\n    .open_in_browser()\n    .build()\n    .wrap_err(\"client creation failed\")?;\n\n    Runtime::new().unwrap().block_on(async move {\n        let token = oauth_client.get_access_token_async().await?;\n        let creds = Credentials::with_access_token(token.access_token);\n\n        let session = Session::new(session_config, Some(cache));\n        session.connect(creds, true).await\n    })?;\n\n    info!(\"\\nLogin successful! You are now ready to run spotifyd.\");\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/process.rs",
    "content": "use crate::error::Error;\nuse librespot_metadata::audio::AudioItem;\nuse librespot_playback::player::PlayerEvent;\nuse log::info;\n\nuse std::{collections::HashMap, process::Stdio};\nuse tokio::{\n    io::{self, AsyncWriteExt},\n    process::{self, Command},\n};\n\n/// Spawns provided command in a subprocess using the provided shell.\nfn spawn_program(shell: &str, cmd: &str, env: HashMap<&str, String>) -> Result<Child, Error> {\n    info!(\n        \"Running {:?} using {:?} with environment variables {:?}\",\n        cmd, shell, env\n    );\n    let inner = Command::new(shell)\n        .arg(\"-c\")\n        .arg(cmd)\n        .envs(env.iter())\n        .stdin(Stdio::piped())\n        .stdout(Stdio::piped())\n        .stderr(Stdio::piped())\n        .spawn()\n        .map_err(|e| Error::subprocess_with_err(shell, cmd, e))?;\n    let child = Child::new(cmd.to_string(), inner, shell.to_string());\n    Ok(child)\n}\n\nfn audio_item_to_env(audio_item: Box<AudioItem>, env: &mut HashMap<&str, String>) {\n    env.insert(\"TRACK_ID\", audio_item.track_id.to_id().unwrap_or_default());\n    env.insert(\"TRACK_NAME\", audio_item.name);\n    env.insert(\"TRACK_DURATION\", audio_item.duration_ms.to_string());\n    if let Some(cover) = audio_item.covers.into_iter().max_by_key(|c| c.width) {\n        env.insert(\"TRACK_COVER\", cover.url);\n    }\n}\n\n/// Spawns provided command in a subprocess using the provided shell.\n/// Various environment variables are included in the subprocess's environment\n/// depending on the `PlayerEvent` that was passed in.\npub(crate) fn spawn_program_on_event(\n    shell: &str,\n    cmd: &str,\n    event: PlayerEvent,\n) -> Result<Child, Error> {\n    let mut env = HashMap::new();\n    match event {\n        PlayerEvent::TrackChanged { audio_item } => {\n            env.insert(\"PLAYER_EVENT\", \"change\".to_string());\n            audio_item_to_env(audio_item, &mut env);\n        }\n        PlayerEvent::Playing {\n            track_id,\n            play_request_id,\n            position_ms,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"start\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n            env.insert(\"POSITION_MS\", position_ms.to_string());\n        }\n        PlayerEvent::Stopped {\n            track_id,\n            play_request_id,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"stop\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n        PlayerEvent::Loading {\n            track_id,\n            play_request_id,\n            position_ms,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"load\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n            env.insert(\"POSITION_MS\", position_ms.to_string());\n        }\n        PlayerEvent::Paused {\n            track_id,\n            play_request_id,\n            position_ms,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"pause\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n            env.insert(\"POSITION_MS\", position_ms.to_string());\n        }\n        PlayerEvent::TimeToPreloadNextTrack {\n            track_id,\n            play_request_id,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"preload\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n        PlayerEvent::EndOfTrack {\n            track_id,\n            play_request_id,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"endoftrack\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n        PlayerEvent::VolumeChanged { volume } => {\n            env.insert(\"PLAYER_EVENT\", \"volumeset\".to_string());\n            env.insert(\"VOLUME\", volume.to_string());\n        }\n        PlayerEvent::Unavailable {\n            play_request_id,\n            track_id,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"unavailable\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n        PlayerEvent::Preloading { track_id } => {\n            env.insert(\"PLAYER_EVENT\", \"preloading\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n        }\n        PlayerEvent::PositionCorrection {\n            play_request_id,\n            track_id,\n            position_ms,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"positioncorrection\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"POSITION_MS\", position_ms.to_string());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n        PlayerEvent::Seeked {\n            play_request_id,\n            track_id,\n            position_ms,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"seeked\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"POSITION_MS\", position_ms.to_string());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n        PlayerEvent::PlayRequestIdChanged { play_request_id } => {\n            env.insert(\"PLAYER_EVENT\", \"playrequestid_changed\".to_string());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n        PlayerEvent::SessionConnected {\n            connection_id,\n            user_name,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"sessionconnected\".to_string());\n            env.insert(\"USERNAME\", user_name);\n            env.insert(\"CONNECTION_ID\", connection_id);\n        }\n        PlayerEvent::SessionDisconnected {\n            connection_id,\n            user_name,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"sessiondisconnected\".to_string());\n            env.insert(\"USERNAME\", user_name);\n            env.insert(\"CONNECTION_ID\", connection_id);\n        }\n        PlayerEvent::SessionClientChanged {\n            client_id,\n            client_name,\n            client_brand_name,\n            client_model_name,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"clientchanged\".to_string());\n            env.insert(\"CLIENT_ID\", client_id);\n            env.insert(\"CLIENT_NAME\", client_name);\n            env.insert(\"CLIENT_BRAND\", client_brand_name);\n            env.insert(\"CLIENT_MODEL\", client_model_name);\n        }\n        PlayerEvent::ShuffleChanged { shuffle } => {\n            env.insert(\"PLAYER_EVENT\", \"shuffle_changed\".to_string());\n            env.insert(\"SHUFFLE\", shuffle.to_string());\n        }\n        PlayerEvent::RepeatChanged { context, track } => {\n            env.insert(\"PLAYER_EVENT\", \"repeat_changed\".to_string());\n            let val = match context {\n                true => match track {\n                    true => \"track\",\n                    false => \"all\",\n                },\n                false => \"none\",\n            }\n            .to_string();\n            env.insert(\"REPEAT\", val);\n        }\n        PlayerEvent::AutoPlayChanged { auto_play } => {\n            env.insert(\"PLAYER_EVENT\", \"autoplay_changed\".to_string());\n            env.insert(\"AUTOPLAY\", auto_play.to_string());\n        }\n        PlayerEvent::FilterExplicitContentChanged { filter } => {\n            env.insert(\"PLAYER_EVENT\", \"filterexplicit_changed\".to_string());\n            env.insert(\"FILTEREXPLICIT\", filter.to_string());\n        }\n        PlayerEvent::PositionChanged {\n            play_request_id,\n            position_ms,\n            track_id,\n        } => {\n            env.insert(\"PLAYER_EVENT\", \"position_changed\".to_string());\n            env.insert(\"TRACK_ID\", track_id.to_id().unwrap());\n            env.insert(\"POSITION_MS\", position_ms.to_string());\n            env.insert(\"PLAY_REQUEST_ID\", play_request_id.to_string());\n        }\n    }\n    spawn_program(shell, cmd, env)\n}\n\n/// Wraps `tokio::process::Child` so that when this `Child` exits:\n/// * successfully: It writes the contents of it's stdout to the stdout of the\n///   main process.\n/// * unsuccesfully: It returns an error that includes the contents it's stderr\n///   as well as information on the command that was run and the shell that\n///   invoked it.\npub(crate) struct Child {\n    cmd: String,\n    child: process::Child,\n    shell: String,\n}\n\nimpl Child {\n    pub(crate) fn new(cmd: String, child: process::Child, shell: String) -> Self {\n        Self { cmd, child, shell }\n    }\n\n    pub(crate) async fn wait(self) -> Result<(), Error> {\n        let Child { cmd, shell, child } = self;\n\n        let output = child\n            .wait_with_output()\n            .await\n            .map_err(|e| Error::subprocess_with_err(&shell, &cmd, e))?;\n\n        if output.status.success() {\n            // If successful, write subprocess's stdout to main process's stdout...\n            let mut stdout = io::stdout();\n\n            stdout\n                .write_all(&output.stdout)\n                .await\n                .map_err(|e| Error::subprocess_with_err(&shell, &cmd, e))?;\n\n            stdout\n                .flush()\n                .await\n                .map_err(|e| Error::subprocess_with_err(&shell, &cmd, e))?;\n\n            Ok(())\n        } else {\n            // If unsuccessful, return an error that includes the contents of stderr...\n            let err = match String::from_utf8(output.stderr) {\n                Ok(stderr) => Error::subprocess_with_str(&shell, &cmd, &stderr),\n                Err(_) => Error::subprocess(&shell, &cmd),\n            };\n            Err(err)\n        }\n    }\n}\n"
  },
  {
    "path": "src/setup.rs",
    "content": "#[cfg(feature = \"alsa_backend\")]\nuse crate::alsa_mixer;\nuse crate::{\n    config,\n    main_loop::{self, CredentialsProvider},\n    utils::Backoff,\n};\nuse color_eyre::{Section, eyre::eyre};\nuse futures::StreamExt as _;\nuse librespot_playback::{\n    audio_backend::{self},\n    mixer::{self, Mixer, MixerConfig},\n};\nuse log::{debug, error, info};\nuse std::{sync::Arc, thread};\n\npub(crate) fn initial_state(\n    config: config::SpotifydConfig,\n) -> color_eyre::Result<main_loop::MainLoop> {\n    let mixer: Arc<dyn Mixer> = {\n        match config.volume_controller {\n            config::VolumeController::None => {\n                info!(\"Using no volume controller.\");\n                Arc::new(crate::no_mixer::NoMixer)\n            }\n            #[cfg(feature = \"alsa_backend\")]\n            config::VolumeController::Alsa | config::VolumeController::AlsaLinear => {\n                let device = config\n                    .alsa_config\n                    .mixer\n                    .as_deref()\n                    .or(config.audio_device.as_deref())\n                    .unwrap_or(\"default\")\n                    .to_string();\n                let control = config\n                    .alsa_config\n                    .control\n                    .as_deref()\n                    .unwrap_or(\"Master\")\n                    .to_string();\n                info!(\"Using alsa volume controller.\");\n                use librespot_playback::config::VolumeCtrl;\n                let volume_ctrl = if matches!(\n                    config.volume_controller,\n                    config::VolumeController::AlsaLinear\n                ) {\n                    VolumeCtrl::Linear\n                } else {\n                    VolumeCtrl::Log(0.0) /* this value is ignored */\n                };\n                Arc::new(alsa_mixer::AlsaMixer::open(MixerConfig {\n                    device,\n                    control,\n                    index: 0,\n                    volume_ctrl,\n                }).with_suggestion(|| {\n                    match alsa_mixer::get_available_controls() {\n                        Err(err) => format!(\"there are no controls available, maybe check that alsa is available: {err}\"),\n                        Ok(controls) => {\n                            format!(\"maybe try one of the following as 'mixer':{}\", controls.filter_map(|hint| hint.name.map(|name| format!(\"\\n- {name}\"))).collect::<String>())\n                        }\n                    }\n                })?)\n            }\n            _ => {\n                info!(\"Using software volume controller.\");\n                let mixer = mixer::softmixer::SoftMixer::open(MixerConfig::default())\n                    .expect(\"SoftMixer::open never returns an Error\");\n                Arc::new(mixer)\n            }\n        }\n    };\n\n    let player_config = config.player_config;\n    let session_config = config.session_config;\n    let backend = config.backend.clone();\n\n    let zeroconf_port = config.zeroconf_port.unwrap_or(0);\n\n    let creds = if let Some(creds) = config.oauth_cache.as_ref().and_then(|c| c.credentials()) {\n        info!(\n            \"Login via OAuth as user {}.\",\n            creds.username.as_deref().unwrap_or(\"unknown\")\n        );\n        Some(creds)\n    } else if let Some(creds) = config.cache.as_ref().and_then(|c| c.credentials()) {\n        info!(\n            \"Restoring previous login as user {}.\",\n            creds.username.as_deref().unwrap_or(\"unknown\")\n        );\n        Some(creds)\n    } else {\n        None\n    };\n\n    let discovery = if config.discovery {\n        info!(\"Starting zeroconf server to advertise on local network.\");\n        debug!(\"Using device id '{}'\", session_config.device_id);\n        let mut retry_backoff = Backoff::default();\n        loop {\n            match librespot_discovery::Discovery::builder(\n                session_config.device_id.clone(),\n                session_config.client_id.clone(),\n            )\n            .name(config.device_name.clone())\n            .device_type(config.device_type)\n            .port(zeroconf_port)\n            .launch()\n            {\n                Ok(discovery_stream) => break Some(discovery_stream),\n                Err(err) => {\n                    error!(\"failed to enable discovery: {err}\");\n                    let Ok(backoff) = retry_backoff.next_backoff() else {\n                        error!(\"maximum amount of retries exceeded\");\n                        break None;\n                    };\n                    info!(\"retrying discovery in {} seconds\", backoff.as_secs());\n                    thread::sleep(backoff);\n                    info!(\n                        \"trying to enable discovery (retry {}/{})\",\n                        retry_backoff.retries(),\n                        retry_backoff.max_retries()\n                    );\n                }\n            }\n        }\n    } else {\n        None\n    };\n\n    let credentials_provider = match (discovery, creds) {\n        (Some(stream), creds) => CredentialsProvider::Discovery {\n            stream: stream.peekable(),\n            last_credentials: creds,\n        },\n        (None, Some(creds)) => CredentialsProvider::CredentialsOnly(creds),\n        (None, None) => {\n            return Err(\n                eyre!(\"Discovery unavailable and no credentials found.\").with_suggestion(\n                    || \"Try enabling discovery or logging in first with `spotifyd authenticate`.\",\n                ),\n            );\n        }\n    };\n\n    let backend = audio_backend::find(backend).expect(\"available backends should match ours\");\n\n    Ok(main_loop::MainLoop {\n        credentials_provider,\n        mixer,\n        session_config,\n        cache: config.cache,\n        audio_device: config.audio_device,\n        audio_format: config.audio_format,\n        player_config,\n        backend,\n        initial_volume: config.initial_volume,\n        disable_volume: false,\n        shell: config.shell,\n        device_type: config.device_type,\n        device_name: config.device_name,\n        player_event_program: config.onevent,\n        #[cfg(feature = \"dbus_mpris\")]\n        mpris_config: config.mpris,\n    })\n}\n"
  },
  {
    "path": "src/utils.rs",
    "content": "use log::trace;\nuse std::{env, time::Duration};\n\n#[cfg(any(\n    target_os = \"freebsd\",\n    target_os = \"linux\",\n    target_os = \"openbsd\",\n    target_os = \"android\"\n))]\nfn get_shell_ffi() -> Option<String> {\n    use libc::{geteuid, getpwuid_r};\n    use std::{ffi::CStr, mem, ptr};\n\n    trace!(\"Retrieving user shell through libc calls\");\n\n    let mut result = ptr::null_mut();\n    unsafe {\n        let amt: usize = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {\n            n if n < 0 => 512,\n            n => n as usize,\n        };\n        let mut buf = Vec::with_capacity(amt);\n        let mut passwd: libc::passwd = mem::zeroed();\n\n        match getpwuid_r(\n            geteuid(),\n            &mut passwd,\n            buf.as_mut_ptr(),\n            buf.capacity() as libc::size_t,\n            &mut result,\n        ) {\n            0 if !result.is_null() => {\n                let ptr = passwd.pw_shell as *const _;\n                let shell = CStr::from_ptr(ptr)\n                    .to_str()\n                    .expect(\"Failed to retrieve shell\")\n                    .to_owned();\n                Some(shell)\n            }\n            _ => None,\n        }\n    }\n}\n\n// If the SHELL environment variable is not set and on we're on macOS,\n// query the Directory Service command line utility (dscl) for the user's shell,\n// as macOS does not use the /etc/passwd file\n#[cfg(target_os = \"macos\")]\nfn get_shell_ffi() -> Option<String> {\n    use std::process::Command;\n\n    trace!(\"Retrieving user shell through Directory Discovery Services\");\n\n    let username = whoami::username();\n    let output = Command::new(\"dscl\")\n        .args([\".\", \"-read\", &format!(\"/Users/{}\", username), \"UserShell\"])\n        .output()\n        .ok()?;\n\n    if output.status.success() {\n        let stdout = std::str::from_utf8(&output.stdout).ok()?;\n        // The output of the dscl command should be:\n        // \"UserShell: /path/to/shell\"\n        if stdout.starts_with(\"UserShell: \") {\n            let shell = stdout.split_whitespace().nth(1)?;\n            return Some(shell.to_string());\n        }\n    }\n\n    None\n}\n\n#[cfg(target_os = \"windows\")]\nfn get_shell_ffi() -> Option<String> {\n    Some(String::from(\"cmd\"))\n}\n\npub(crate) fn get_shell() -> Option<String> {\n    let shell = env::var(\"SHELL\").ok().or_else(get_shell_ffi);\n    trace!(\"Found user shell: {:?}\", &shell);\n\n    shell\n}\n\n/// Implements basic exponential backoff.\n/// The used base is 2.\npub(crate) struct Backoff {\n    retry_counter: u8,\n    max_retries: u8,\n    initial_backoff: Duration,\n}\n\nimpl Backoff {\n    pub(crate) fn new(max_retries: u8, initial_backoff: Duration) -> Self {\n        Self {\n            retry_counter: 0,\n            max_retries,\n            initial_backoff,\n        }\n    }\n\n    /// Get the next backoff duration.\n    ///\n    /// Increases the retry counter and returns the next required backoff duration,\n    /// if available.\n    pub(crate) fn next_backoff(&mut self) -> Result<Duration, ()> {\n        if self.retry_counter >= self.max_retries {\n            return Err(());\n        }\n        let backoff_duration = self.initial_backoff * 2u32.pow(self.retry_counter as u32);\n        self.retry_counter += 1;\n        Ok(backoff_duration)\n    }\n\n    pub(crate) fn retries(&self) -> u8 {\n        self.retry_counter\n    }\n\n    pub(crate) fn max_retries(&self) -> u8 {\n        self.max_retries\n    }\n}\n\nimpl Default for Backoff {\n    fn default() -> Self {\n        Self::new(4, Duration::from_secs(5))\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    fn init_logger() {\n        let _ = env_logger::builder().is_test(true).try_init();\n    }\n\n    #[test]\n    fn test_envvar_discovery() {\n        init_logger();\n\n        // SAFETY: this is part of the single-threaded tests\n        unsafe {\n            env::set_var(\"SHELL\", \"fantasy_shell\");\n        }\n\n        let shell = get_shell().unwrap();\n        assert_eq!(shell, \"fantasy_shell\");\n    }\n\n    #[test]\n    fn test_ffi_discovery() {\n        init_logger();\n\n        let shell = get_shell_ffi();\n        assert!(shell.is_some());\n    }\n}\n"
  }
]