File: snapclient.cpp

package info (click to toggle)
snapcast 0.34.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,252 kB
  • sloc: cpp: 40,067; python: 3,260; sh: 455; makefile: 16
file content (604 lines) | stat: -rw-r--r-- 24,394 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/***
    This file is part of snapcast
    Copyright (C) 2014-2025  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 <http://www.gnu.org/licenses/>.
***/

// local headers
#include "common/base64.h"
#include "common/popl.hpp"
#include "common/utils/string_utils.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
#ifdef HAS_PIPEWIRE
#include "player/pipewire_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/stream_uri.hpp"
#include "common/version.hpp"

// 3rd party headers
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/signal_set.hpp>

// standard headers
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <vector>
#ifndef WINDOWS
#include <csignal>
#include <sys/resource.h>
#endif


using namespace std;
using namespace popl;
using namespace player;

using namespace std::chrono_literals;

static constexpr auto LOG_TAG = "Snapclient";

namespace
{
PcmDevice getPcmDevice(const std::string& player, const std::string& parameter, const std::string& soundcard)
{
    LOG(DEBUG, LOG_TAG) << "Trying to get PCM device for player: " << player << ", parameter: " << ", card: " << soundcard << "\n";
#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) || defined(HAS_PIPEWIRE)
    vector<PcmDevice> pcm_devices;
#if defined(HAS_ALSA)
    if (player == player::ALSA)
        pcm_devices = AlsaPlayer::pcm_list();
#endif
#if defined(HAS_PULSE)
    if (player == player::PULSE)
        pcm_devices = PulsePlayer::pcm_list(parameter);
#endif
#if defined(HAS_WASAPI)
    if (player == player::WASAPI)
        pcm_devices = WASAPIPlayer::pcm_list();
#endif
#if defined(HAS_PIPEWIRE)
    if (player == player::PIPEWIRE)
        pcm_devices = PipeWirePlayer::pcm_list(parameter);
#endif
    if (player == player::FILE)
        return FilePlayer::pcm_list(parameter).front();
    try
    {
        // If "soundcard" can be converted to an integer,
        // try to map the device by index
        int soundcardIdx = cpt::stoi(soundcard);
        for (const auto& dev : pcm_devices)
            if (dev.idx == soundcardIdx)
                return dev;
    }
    catch (...)
    {
    }

    for (const 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;
}
} // namespace

#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

#ifdef HAS_MDNS
    const std::string default_uri = "tcp://_snapcast._tcp";
#endif

    int exitcode = EXIT_SUCCESS;
    try
    {
        ClientSettings settings;
        string pcm_device(player::DEFAULT_DEVICE);

        OptionParser op("Usage: snapclient [options...] [url]\n\n"
                        " With 'url' = "
#ifdef HAS_OPENSSL
                        "<tcp|ws|wss>"
#else
                        "<tcp|ws>"
#endif
#ifdef HAS_MDNS
                        "://<snapserver host or IP or mDNS service name>[:port]\n"
                        " For example: 'tcp://192.168.1.1:1704', or 'ws://)homeserver.local' or 'wss://_snapcast-https._tcp'\n"
                        " If 'url' is not configured, snapclient defaults to '" +
                        default_uri + "'\n");
#else
                        "://<snapserver host or IP>[:port]\n"
                        " For example: 'tcp://192.168.1.1:1704', or 'ws://homeserver.local'\n");
#endif
        auto helpSwitch = op.add<Switch>("", "help", "Produce help message");
        auto groffSwitch = op.add<Switch, Attribute::hidden>("", "groff", "Produce groff message");
        auto versionSwitch = op.add<Switch>("v", "version", "Show version number");
        auto deprecated_host_opt = op.add<Value<string>>("h", "host", "(deprecated, use [url]) Server hostname or ip address", "");
        auto deprecated_port_opt = op.add<Value<size_t>>("p", "port", "(deprecated, use [url]) Server port", 1704);
        op.add<Value<size_t>>("i", "instance", "Instance id when running multiple instances on the same host", 1, &settings.instance);
        op.add<Value<string>>("", "hostID", "Unique host id, default is MAC address", "", &settings.host_id);
        op.add<Value<std::filesystem::path>>("", "cert", "Client certificate file (PEM format)", settings.server.certificate, &settings.server.certificate);
        op.add<Value<std::filesystem::path>>("", "cert-key", "Client private key file (PEM format)", settings.server.certificate_key,
                                             &settings.server.certificate_key);
        op.add<Value<string>>("", "key-password", "Key password (for encrypted private key)", settings.server.key_password, &settings.server.key_password);
        auto server_cert_opt =
            op.add<Implicit<std::filesystem::path>>("", "server-cert", "Verify server with CA certificate (PEM format)", "default certificates");

// PCM device specific
#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) || defined(HAS_PIPEWIRE)
        auto listSwitch = op.add<Switch>("l", "list", "List PCM devices");
        op.add<Value<string>>("s", "soundcard", "Index or name of the PCM device", pcm_device, &pcm_device);
#endif
        op.add<Value<int>>("", "latency", "Latency of the PCM device", 0, &settings.player.latency);
#ifdef HAS_SOXR
        auto sample_format = op.add<Value<string>>("", "sampleformat", "Resample audio stream to <rate>:<bits>:<channels>", "");
#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<Value<string>>("", "player", supported_players_str + "[:<options>|?]", supported_players.front(), &settings.player.player_name);

// sharing mode
#if defined(HAS_OBOE) || defined(HAS_WASAPI)
        auto sharing_mode = op.add<Value<string>>("", "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<popl::Value<std::string>> mixer_mode;

        std::string mixers = "software";
        if (hw_mixer_supported)
            mixers += "|hardware";
#ifdef SUPPORTS_VOLUME_SCRIPT
        mixers += "|script";
#endif
        mixer_mode = op.add<Value<string>>("", "mixer", mixers + "|none|?[:<options>]", "software");

// daemon settings
#ifdef HAS_DAEMON
        int processPriority(-3);
        auto daemonOption = op.add<Implicit<int>>("d", "daemon", "Daemonize, optional process priority [-20..19]", processPriority, &processPriority);
        auto userValue = op.add<Value<string>>("", "user", "The user[:group] to run snapclient as when daemonized");
#endif

        // logging
        op.add<Value<string>>("", "logsink", "Log sink [null,system,stdout,stderr,file:<filename>]", settings.logging.sink, &settings.logging.sink);
        auto logfilterOption = op.add<Value<string>>(
            "", "logfilter", "Log filter <tag>:<level>[,<tag>:<level>]* with tag = * or <log tag> 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() << "\n";
            cout << "\n" << op << "\n";
            exit(EXIT_FAILURE);
        }

        if (versionSwitch->is_set())
        {
            cout << "snapclient v" << version::code << (!version::rev().empty() ? (" (rev " + version::rev(8) + ")") : ("")) << "\n"
                 << "Copyright (C) 2014-2025 BadAix (snapcast@badaix.de).\n"
                 << "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\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 <https://github.com/badaix/snapcast/graphs/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) || defined(HAS_PIPEWIRE)
        if (listSwitch->is_set())
        {
            try
            {
                vector<PcmDevice> 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
#if defined(HAS_PIPEWIRE)
                if (settings.player.player_name == player::PIPEWIRE)
                    pcm_devices = PipeWirePlayer::pcm_list(settings.player.parameter);
#endif
#ifdef WINDOWS
                // Set console code page to UTF-8 so console known how to interpret string data
                SetConsoleOutputCP(CP_UTF8);
                // Enable buffering to prevent VS from chopping up UTF-8 byte sequences
                setvbuf(stdout, nullptr, _IOFBF, 1000);
#endif
                for (const auto& dev : pcm_devices)
                    cout << dev.idx << ": " << dev.name << "\n" << dev.description << "\n\n";

                if (pcm_devices.empty())
                    cout << "No PCM device available for audio backend \"" << settings.player.player_name << "\"\n";
            }
            catch (const std::exception& e)
            {
                cout << "Failed to get device list: " << e.what() << "\n";
            }
            exit(EXIT_SUCCESS);
        }
#endif

        if (helpSwitch->is_set())
        {
            cout << op << "\n";
            exit(EXIT_SUCCESS);
        }

        if (groffSwitch->is_set())
        {
            GroffOptionPrinter option_printer(&op);
            cout << option_printer.print();
            exit(EXIT_SUCCESS);
        }

        settings.logging.filter = logfilterOption->value();
        if (logfilterOption->is_set())
        {
            for (size_t n = 1; n < logfilterOption->count(); ++n)
                settings.logging.filter += "," + logfilterOption->value(n);
        }

        if (settings.logging.sink.empty())
        {
            settings.logging.sink = "stdout";
#ifdef HAS_DAEMON
            if (daemonOption->is_set())
                settings.logging.sink = "system";
#endif
        }
        AixLog::Filter logfilter;
        auto filters = utils::string::split(settings.logging.filter, ',');
        for (const auto& filter : filters)
            logfilter.add_filter(filter);

        string logformat = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)";
        if (settings.logging.sink.find("file:") != string::npos)
        {
            string logfile = settings.logging.sink.substr(settings.logging.sink.find(':') + 1);
            AixLog::Log::init<AixLog::SinkFile>(logfilter, logfile, logformat);
        }
        else if (settings.logging.sink == "stdout")
            AixLog::Log::init<AixLog::SinkCout>(logfilter, logformat);
        else if (settings.logging.sink == "stderr")
            AixLog::Log::init<AixLog::SinkCerr>(logfilter, logformat);
        else if (settings.logging.sink == "system")
            AixLog::Log::init<AixLog::SinkNative>("snapclient", logfilter);
        else if (settings.logging.sink == "null")
            AixLog::Log::init<AixLog::SinkNull>();
        else
            throw SnapException("Invalid log sink: " + settings.logging.sink);

        if (!op.unknown_options().empty())
        {
            throw SnapException("Unknown command line argument: '" + op.unknown_options().front() + "'");
        }

        if (deprecated_host_opt->is_set() || deprecated_port_opt->is_set())
        {
            LOG(WARNING, LOG_TAG) << "Options '--" << deprecated_host_opt->long_name() << "' and '--" << deprecated_port_opt->long_name()
                                  << "' are deprecated. Please add the server URI as last command line argument\n";
            settings.server.uri.host = deprecated_host_opt->value();
            settings.server.uri.port = deprecated_port_opt->value();
            settings.server.uri.scheme = "tcp";
        }

        if (!op.non_option_args().empty())
        {
            std::vector<std::string> schemes{"tcp", "ws"};
#ifdef HAS_OPENSSL
            schemes.emplace_back("wss");
#endif
            try
            {
                settings.server.uri.parse(op.non_option_args().front());
            }
            catch (...)
            {
                throw SnapException("Invalid URI - expected format: \"<scheme>://<host or IP>[:port]\", with 'scheme' one of: " +
                                    utils::string::container_to_string(schemes));
            }

            if (std::find(schemes.begin(), schemes.end(), settings.server.uri.scheme) == schemes.end())
                throw SnapException("Protocol must be one of: " + utils::string::container_to_string(schemes));

            if (!settings.server.uri.port.has_value())
            {
                if (settings.server.uri.scheme == "tcp")
                    settings.server.uri.port = 1704;
                else if (settings.server.uri.scheme == "ws")
                    settings.server.uri.port = 1780;
                else if (settings.server.uri.scheme == "wss")
                    settings.server.uri.port = 1788;
            }

            if (!settings.server.uri.user.empty() || !settings.server.uri.password.empty())
            {
                ClientSettings::Server::Auth auth;
                auth.scheme = "Basic";
                auth.param = base64_encode(settings.server.uri.user + ":" + settings.server.uri.password);
                settings.server.auth = auth;
            }
        }

        if (server_cert_opt->is_set())
        {
            if (server_cert_opt->get_default() == server_cert_opt->value())
                settings.server.server_certificate = "";
            else
                settings.server.server_certificate = std::filesystem::weakly_canonical(server_cert_opt->value());
            if (settings.server.server_certificate.value_or("").empty())
                LOG(INFO, LOG_TAG) << "Server certificate: default certificates\n";
            else
                LOG(INFO, LOG_TAG) << "Server certificate: " << settings.server.server_certificate.value_or("") << "\n";
        }

        if (!settings.server.certificate.empty() && !settings.server.certificate_key.empty())
        {
            namespace fs = std::filesystem;
            settings.server.certificate = fs::weakly_canonical(settings.server.certificate);
            if (!fs::exists(settings.server.certificate))
                throw SnapException("Certificate file not found: " + settings.server.certificate.string());
            settings.server.certificate_key = fs::weakly_canonical(settings.server.certificate_key);
            if (!fs::exists(settings.server.certificate_key))
                throw SnapException("Certificate_key file not found: " + settings.server.certificate_key.string());
        }
        else if (settings.server.certificate.empty() != settings.server.certificate_key.empty())
        {
            throw SnapException("Both SSL 'certificate' and 'certificate_key' must be set or empty");
        }

        if (settings.server.uri.host.empty())
        {
#ifndef HAS_MDNS
            throw SnapException("Snapserver host not configured and mDNS not available, please configure with \"--host\".");
#else
            LOG(INFO, LOG_TAG) << "No server URL given, defaulting to '" << default_uri << "'\n";
            settings.server.uri.parse(default_uri);
#endif
        }


#ifdef HAS_DAEMON
        std::unique_ptr<Daemon> 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<string> user_group = utils::string::split(userValue->value(), ':');
                user = user_group[0];
                if (user_group.size() > 1)
                    group = user_group[1];
            }
            daemon = std::make_unique<Daemon>(user, group, pidFile);
            processPriority = std::min(std::max(-20, processPriority), 19);
            if (processPriority != 0)
                setpriority(PRIO_PROCESS, 0, processPriority);
            LOG(NOTICE, LOG_TAG) << "daemonizing\n";
            daemon->daemonize();
            LOG(NOTICE, LOG_TAG) << "daemon started\n";
        }
#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=<filename>\" - with <filename> = \"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=<buffer size [ms]>\" - default 100, min 10\n"
                     << " \"server=<PulseAudio server>\" - default not-set: use the default server\n"
                     << " \"property=<key>=<value>\" - can be set multiple times, default 'media.role=music'\n";
            }
#endif
#ifdef HAS_ALSA
            else if (settings.player.player_name == player::ALSA)
            {
                cout << "Options are a comma separated list of:\n"
                     << " \"buffer_time=<total buffer size [ms]>\" - default 80, min 10\n"
                     << " \"fragments=<number of buffers>\" - default 4, min 2\n";
            }
#endif
#ifdef HAS_PIPEWIRE
            else if (settings.player.player_name == player::PIPEWIRE)
            {
                cout << "Options are:\n"
                     << " \"buffer_time=<total buffer size [ms]>\" - default <not set, PipeWire will decide>, min 10\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)
        {
#if defined(HAS_PIPEWIRE)
            if (settings.player.player_name != player::PIPEWIRE)
#endif
                LOG(ERROR, LOG_TAG) << "PCM device \"" << pcm_device << "\" not found\n";
            // exit(EXIT_FAILURE);
        }
#endif

        string mode = utils::string::split_left(mixer_mode->value(), ':', settings.player.mixer.parameter);
        if (mode == "software")
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::software;
        else if ((mode == "hardware") && hw_mixer_supported)
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::hardware;
#ifdef SUPPORTS_VOLUME_SCRIPT
        else if (mode == "script")
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::script;
#endif
        else if (mode == "none")
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::none;
        else if ((mode == "?") || (mode == "help"))
        {
            cout << "mixer can be one of 'software', " << (hw_mixer_supported ? "'hardware', " : "")
#ifdef SUPPORTS_VOLUME_SCRIPT
                 << "'script', "
#endif
                 << "'none'\n"
                 << "followed by optional parameters:\n"
                 << " * software[:poly[:<exponent>]|exp[:<base>]]\n"
                 << (hw_mixer_supported ? " * hardware[:<mixer name>]\n" : "")
#ifdef SUPPORTS_VOLUME_SCRIPT
                 << " * script[:<script filename>]"
#endif
                 << "\n";
            exit(EXIT_SUCCESS);
        }
        else
            throw SnapException("Mixer mode not supported: " + mode);

        boost::asio::io_context io_context;
        // Construct a signal set registered for process termination.
        boost::asio::signal_set signals(io_context, SIGHUP, SIGINT, SIGTERM);
        signals.async_wait([&](const boost::system::error_code& ec, int signal)
        {
            if (!ec)
                LOG(INFO, LOG_TAG) << "Received signal " << signal << ": " << strsignal(signal) << "\n";
            else
                LOG(INFO, LOG_TAG) << "Failed to wait for signal, error: " << ec.message() << "\n";
            io_context.stop();
        });

        LOG(INFO, LOG_TAG) << "Version " << version::code << (!version::rev().empty() ? (", revision " + version::rev(8)) : ("")) << "\n";

        auto controller = make_shared<Controller>(io_context, settings);
        controller->start();

        int num_threads = 0;
        std::vector<std::thread> threads;
        threads.reserve(num_threads);
        for (int n = 0; n < num_threads; ++n)
            threads.emplace_back([&] { io_context.run(); });
        io_context.run();
        for (auto& t : threads)
            t.join();
    }
    catch (const std::exception& e)
    {
        LOG(FATAL, LOG_TAG) << "Exception: " << e.what() << "\n";
        exitcode = EXIT_FAILURE;
    }

    LOG(NOTICE, LOG_TAG) << "Snapclient terminated.\n";
    exit(exitcode);
}