/*** This file is part of snapcast Copyright (C) 2014-2021 Johannes Pohl This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ***/ #include #include #ifndef WINDOWS #include #include #endif #include "common/popl.hpp" #include "controller.hpp" #ifdef HAS_ALSA #include "player/alsa_player.hpp" #endif #ifdef HAS_PULSE #include "player/pulse_player.hpp" #endif #ifdef HAS_WASAPI #include "player/wasapi_player.hpp" #endif #include "player/file_player.hpp" #ifdef HAS_DAEMON #include "common/daemon.hpp" #endif #include "client_settings.hpp" #include "common/aixlog.hpp" #include "common/snap_exception.hpp" #include "common/str_compat.hpp" #include "common/utils.hpp" #include "metadata.hpp" using namespace std; using namespace popl; using namespace player; using namespace std::chrono_literals; static constexpr auto LOG_TAG = "Snapclient"; PcmDevice getPcmDevice(const std::string& player, const std::string& parameter, const std::string& soundcard) { #if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) vector pcm_devices; #if defined(HAS_ALSA) if (player == player::ALSA) pcm_devices = AlsaPlayer::pcm_list(); #endif #if defined(HAS_PULSE) if (player == player::PULSE) pcm_devices = PulsePlayer::pcm_list(parameter); #endif #if defined(HAS_WASAPI) if (player == player::WASAPI) pcm_devices = WASAPIPlayer::pcm_list(); #endif try { int soundcardIdx = cpt::stoi(soundcard); for (auto dev : pcm_devices) if (dev.idx == soundcardIdx) return dev; } catch (...) { } for (auto dev : pcm_devices) if (dev.name.find(soundcard) != string::npos) return dev; #endif std::ignore = player; std::ignore = parameter; PcmDevice pcm_device; pcm_device.name = soundcard; return pcm_device; } #ifdef WINDOWS // hack to avoid case destinction in the signal handler #define SIGHUP SIGINT const char* strsignal(int sig) { switch (sig) { case SIGTERM: return "SIGTERM"; case SIGINT: return "SIGINT"; case SIGBREAK: return "SIGBREAK"; case SIGABRT: return "SIGABRT"; default: return "Unhandled"; } } #endif int main(int argc, char** argv) { #ifdef MACOS #pragma message "Warning: the macOS support is experimental and might not be maintained" #endif int exitcode = EXIT_SUCCESS; try { string meta_script; ClientSettings settings; string pcm_device(player::DEFAULT_DEVICE); OptionParser op("Allowed options"); auto helpSwitch = op.add("", "help", "produce help message"); auto groffSwitch = op.add("", "groff", "produce groff message"); auto versionSwitch = op.add("v", "version", "show version number"); op.add>("h", "host", "server hostname or ip address", "", &settings.server.host); op.add>("p", "port", "server port", 1704, &settings.server.port); op.add>("i", "instance", "instance id when running multiple instances on the same host", 1, &settings.instance); op.add>("", "hostID", "unique host id, default is MAC address", "", &settings.host_id); // PCM device specific #if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) auto listSwitch = op.add("l", "list", "list PCM devices"); /*auto soundcardValue =*/op.add>("s", "soundcard", "index or name of the pcm device", pcm_device, &pcm_device); #endif /*auto latencyValue =*/op.add>("", "latency", "latency of the PCM device", 0, &settings.player.latency); #ifdef HAS_SOXR auto sample_format = op.add>("", "sampleformat", "resample audio stream to ::", ""); #endif auto supported_players = Controller::getSupportedPlayerNames(); string supported_players_str; for (const auto& supported_player : supported_players) supported_players_str += (!supported_players_str.empty() ? "|" : "") + supported_player; op.add>("", "player", supported_players_str + "[:|?]", supported_players.front(), &settings.player.player_name); // sharing mode #if defined(HAS_OBOE) || defined(HAS_WASAPI) auto sharing_mode = op.add>("", "sharingmode", "audio mode to use [shared|exclusive]", "shared"); #endif // mixer bool hw_mixer_supported = false; #if defined(HAS_ALSA) hw_mixer_supported = true; #endif std::shared_ptr> mixer_mode; if (hw_mixer_supported) mixer_mode = op.add>("", "mixer", "software|hardware|script|none|?[:]", "software"); else mixer_mode = op.add>("", "mixer", "software|script|none|?[:]", "software"); auto metaStderr = op.add("e", "mstderr", "send metadata to stderr"); // daemon settings #ifdef HAS_DAEMON int processPriority(-3); auto daemonOption = op.add>("d", "daemon", "daemonize, optional process priority [-20..19]", processPriority, &processPriority); auto userValue = op.add>("", "user", "the user[:group] to run snapclient as when daemonized"); #endif // logging op.add>("", "logsink", "log sink [null,system,stdout,stderr,file:]", settings.logging.sink, &settings.logging.sink); auto logfilterOption = op.add>( "", "logfilter", "log filter :[,:]* with tag = * or and level = [trace,debug,info,notice,warning,error,fatal]", settings.logging.filter); try { op.parse(argc, argv); } catch (const std::invalid_argument& e) { cerr << "Exception: " << e.what() << std::endl; cout << "\n" << op << "\n"; exit(EXIT_FAILURE); } if (versionSwitch->is_set()) { cout << "snapclient v" << VERSION << "\n" << "Copyright (C) 2014-2021 BadAix (snapcast@badaix.de).\n" << "License GPLv3+: GNU GPL version 3 or later .\n" << "This is free software: you are free to change and redistribute it.\n" << "There is NO WARRANTY, to the extent permitted by law.\n\n" << "Written by Johannes M. Pohl and contributors .\n\n"; exit(EXIT_SUCCESS); } settings.player.player_name = utils::string::split_left(settings.player.player_name, ':', settings.player.parameter); #if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) if (listSwitch->is_set()) { try { vector pcm_devices; #if defined(HAS_ALSA) if (settings.player.player_name == player::ALSA) pcm_devices = AlsaPlayer::pcm_list(); #endif #if defined(HAS_PULSE) if (settings.player.player_name == player::PULSE) pcm_devices = PulsePlayer::pcm_list(settings.player.parameter); #endif #if defined(HAS_WASAPI) if (settings.player.player_name == player::WASAPI) pcm_devices = WASAPIPlayer::pcm_list(); #endif #ifdef WINDOWS // Set console code page to UTF-8 so console known how to interpret string data SetConsoleOutputCP(CP_UTF8); // Enable buffering to prevent VS from chopping up UTF-8 byte sequences setvbuf(stdout, nullptr, _IOFBF, 1000); #endif for (const auto& dev : pcm_devices) cout << dev.idx << ": " << dev.name << "\n" << dev.description << "\n\n"; if (pcm_devices.empty()) cout << "No PCM device available for audio backend \"" << settings.player.player_name << "\"\n"; } catch (const std::exception& e) { cout << "Failed to get device list: " << e.what() << "\n"; } exit(EXIT_SUCCESS); } #endif if (helpSwitch->is_set()) { cout << op << "\n"; exit(EXIT_SUCCESS); } if (groffSwitch->is_set()) { GroffOptionPrinter option_printer(&op); cout << option_printer.print(); exit(EXIT_SUCCESS); } // XXX: Only one metadata option must be set settings.logging.filter = logfilterOption->value(); if (logfilterOption->is_set()) { for (size_t n = 1; n < logfilterOption->count(); ++n) settings.logging.filter += "," + logfilterOption->value(n); } if (settings.logging.sink.empty()) { settings.logging.sink = "stdout"; #ifdef HAS_DAEMON if (daemonOption->is_set()) settings.logging.sink = "system"; #endif } AixLog::Filter logfilter; auto filters = utils::string::split(settings.logging.filter, ','); for (const auto& filter : filters) logfilter.add_filter(filter); string logformat = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)"; if (settings.logging.sink.find("file:") != string::npos) { string logfile = settings.logging.sink.substr(settings.logging.sink.find(':') + 1); AixLog::Log::init(logfilter, logfile, logformat); } else if (settings.logging.sink == "stdout") AixLog::Log::init(logfilter, logformat); else if (settings.logging.sink == "stderr") AixLog::Log::init(logfilter, logformat); else if (settings.logging.sink == "system") AixLog::Log::init("snapclient", logfilter); else if (settings.logging.sink == "null") AixLog::Log::init(); else throw SnapException("Invalid log sink: " + settings.logging.sink); #if !defined(HAS_AVAHI) && !defined(HAS_BONJOUR) if (settings.server.host.empty()) throw SnapException("Snapserver host not configured and mDNS not available, please configure with \"--host\"."); #endif #ifdef HAS_DAEMON std::unique_ptr daemon; if (daemonOption->is_set()) { string pidFile = "/var/run/snapclient/pid"; if (settings.instance != 1) pidFile += "." + cpt::to_string(settings.instance); string user; string group; if (userValue->is_set()) { if (userValue->value().empty()) throw std::invalid_argument("user must not be empty"); vector user_group = utils::string::split(userValue->value(), ':'); user = user_group[0]; if (user_group.size() > 1) group = user_group[1]; } daemon = std::make_unique(user, group, pidFile); processPriority = std::min(std::max(-20, processPriority), 19); if (processPriority != 0) setpriority(PRIO_PROCESS, 0, processPriority); LOG(NOTICE, LOG_TAG) << "daemonizing" << std::endl; daemon->daemonize(); LOG(NOTICE, LOG_TAG) << "daemon started" << std::endl; } #endif #ifdef HAS_SOXR if (sample_format->is_set()) { settings.player.sample_format = SampleFormat(sample_format->value()); if (settings.player.sample_format.channels() != 0) throw SnapException("sampleformat channels must be * (= same as the source)"); auto bits = settings.player.sample_format.bits(); if ((bits != 0) && (bits != 16) && (bits != 24) && (bits != 32)) throw SnapException("sampleformat bits must be 16, 24, 32, * (= same as the source)"); } #endif #if defined(HAS_OBOE) || defined(HAS_WASAPI) settings.player.sharing_mode = (sharing_mode->value() == "exclusive") ? ClientSettings::SharingMode::exclusive : ClientSettings::SharingMode::shared; #endif if (settings.player.parameter == "?") { if (settings.player.player_name == player::FILE) { cout << "Options are a comma separated list of:\n" << " \"filename=\" - with = \"stdout\", \"stderr\", \"null\" or a filename\n" << " \"mode=[w|a]\" - w: write (discarding the content), a: append (keeping the content)\n"; } #ifdef HAS_PULSE else if (settings.player.player_name == player::PULSE) { cout << "Options are a comma separated list of:\n" << " \"buffer_time=\" - default 100, min 10\n" << " \"server=\" - default not-set: use the default server\n"; } #endif #ifdef HAS_ALSA else if (settings.player.player_name == player::ALSA) { cout << "Options are a comma separated list of:\n" << " \"buffer_time=\" - default 80, min 10\n" << " \"fragments=\" - default 4, min 2\n"; } #endif else { cout << "No options available for \"" << settings.player.player_name << "\n"; } exit(EXIT_SUCCESS); } settings.player.pcm_device = getPcmDevice(settings.player.player_name, settings.player.parameter, pcm_device); #if defined(HAS_ALSA) if (settings.player.pcm_device.idx == -1) { cout << "PCM device \"" << pcm_device << "\" not found\n"; // exit(EXIT_FAILURE); } #endif string mode = utils::string::split_left(mixer_mode->value(), ':', settings.player.mixer.parameter); if (mode == "software") settings.player.mixer.mode = ClientSettings::Mixer::Mode::software; else if ((mode == "hardware") && hw_mixer_supported) settings.player.mixer.mode = ClientSettings::Mixer::Mode::hardware; else if (mode == "script") settings.player.mixer.mode = ClientSettings::Mixer::Mode::script; else if (mode == "none") settings.player.mixer.mode = ClientSettings::Mixer::Mode::none; else if ((mode == "?") || (mode == "help")) { cout << "mixer can be one of 'software', " << (hw_mixer_supported ? "'hardware', " : "") << "'script', 'none'\n" << "followed by optional parameters:\n" << " * software[:poly[:]|exp[:]]\n" << (hw_mixer_supported ? " * hardware[:]\n" : "") << " * script[: