2 * Shairport, an Apple Airplay receiver
3 * Copyright (c) James Laird 2013
5 * Modifications and additions (c) Mike Brady 2014--2022
7 * Permission is hereby granted, free of charge, to any person
8 * obtaining a copy of this software and associated documentation
9 * files (the "Software"), to deal in the Software without
10 * restriction, including without limitation the rights to use,
11 * copy, modify, merge, publish, distribute, sublicense, and/or
12 * sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be
16 * included in all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 * OTHER DEALINGS IN THE SOFTWARE.
31 #include <libconfig.h>
38 #include <sys/socket.h>
40 #include <sys/types.h>
46 #ifdef CONFIG_AIRPLAY_2
47 #include "ptp-utilities.h"
49 #include <libavcodec/avcodec.h>
51 #include <uuid/uuid.h>
55 #include <mbedtls/md5.h>
56 #include <mbedtls/version.h>
59 #ifdef CONFIG_POLARSSL
60 #include <polarssl/md5.h>
64 #include <openssl/md5.h>
67 #if defined(CONFIG_DBUS_INTERFACE)
71 #include "activity_monitor.h"
77 #if defined(CONFIG_DACP_CLIENT)
81 #if defined(CONFIG_METADATA_HUB)
82 #include "metadata_hub.h"
85 #ifdef CONFIG_DBUS_INTERFACE
86 #include "dbus-service.h"
93 #ifdef CONFIG_MPRIS_INTERFACE
94 #include "mpris-service.h"
97 #ifdef CONFIG_LIBDAEMON
98 #include <libdaemon/dexec.h>
99 #include <libdaemon/dfork.h>
100 #include <libdaemon/dlog.h>
101 #include <libdaemon/dpid.h>
102 #include <libdaemon/dsignal.h>
112 #ifdef CONFIG_CONVOLUTION
113 #include <FFTConvolver/convolver.h>
117 #ifdef CONFIG_LIBDAEMON
118 int this_is_the_daemon_process
= 0;
122 #define UUID_STR_LEN 36
125 #define strnull(s) ((s) ? (s) : "(null)")
127 pthread_t rtsp_listener_thread
;
130 int daemonisewith
= 0;
131 int daemonisewithout
= 0;
132 int log_to_syslog_selected
= 0;
133 int log_to_syslog_select_is_first_command_line_argument
= 0;
135 // static int shutting_down = 0;
136 char configuration_file_path
[4096 + 1];
137 char actual_configuration_file_path
[4096 + 1];
139 char first_backend_name
[256];
141 void print_version(void) {
142 char *version_string
= get_version_string();
143 if (version_string
) {
144 printf("%s\n", version_string
);
145 free(version_string
);
147 debug(1, "Can't print version string!");
151 #ifdef CONFIG_AIRPLAY_2
152 int has_fltp_capable_aac_decoder(void) {
154 // return 1 if the AAC decoder advertises fltp decoding capability, which
155 // is needed for decoding Buffered Audio streams
156 int has_capability
= 0;
157 const AVCodec
*codec
= avcodec_find_decoder(AV_CODEC_ID_AAC
);
159 const enum AVSampleFormat
*p
= codec
->sample_fmts
;
161 while ((has_capability
== 0) && (*p
!= AV_SAMPLE_FMT_NONE
)) {
162 if (*p
== AV_SAMPLE_FMT_FLTP
)
168 return has_capability
;
173 pthread_t soxr_time_check_thread
;
174 void *soxr_time_check(__attribute__((unused
)) void *arg
) {
175 const int buffer_length
= 352;
176 int32_t inbuffer
[buffer_length
* 2];
177 int32_t outbuffer
[(buffer_length
+ 1) * 2];
179 // int32_t *outbuffer = (int32_t*)malloc((buffer_length+1)*2*sizeof(int32_t));
180 // int32_t *inbuffer = (int32_t*)malloc((buffer_length)*2*sizeof(int32_t));
182 // generate a sample signal
183 const double frequency
= 440; //
187 int number_of_iterations
= 0;
188 uint64_t soxr_start_time
= get_absolute_time_in_ns();
189 uint64_t loop_until_time
=
190 (uint64_t)1500000000 + soxr_start_time
; // loop for a second and a half, max -- no need to be
191 // able to cancel it, do _don't even try_!
192 while (get_absolute_time_in_ns() < loop_until_time
) {
194 number_of_iterations
++;
195 for (i
= 0; i
< buffer_length
; i
++) {
196 double w
= sin(i
* (frequency
+ number_of_iterations
* 2) * 2 * M_PI
/ 44100);
197 int32_t wint
= (int32_t)(w
* INT32_MAX
);
198 inbuffer
[i
* 2] = wint
;
199 inbuffer
[i
* 2 + 1] = wint
;
202 soxr_io_spec_t io_spec
;
203 io_spec
.itype
= SOXR_INT32_I
;
204 io_spec
.otype
= SOXR_INT32_I
;
205 io_spec
.scale
= 1.0; // this seems to crash if not = 1.0
211 soxr_oneshot(buffer_length
, buffer_length
+ 1, 2, // Rates and # of chans.
212 inbuffer
, buffer_length
, NULL
, // Input.
213 outbuffer
, buffer_length
+ 1, &odone
, // Output.
214 &io_spec
, // Input, output and transfer spec.
215 NULL
, NULL
); // Default configuration.
217 io_spec
.itype
= SOXR_INT32_I
;
218 io_spec
.otype
= SOXR_INT32_I
;
219 io_spec
.scale
= 1.0; // this seems to crash if not = 1.0
223 soxr_oneshot(buffer_length
, buffer_length
- 1, 2, // Rates and # of chans.
224 inbuffer
, buffer_length
, NULL
, // Input.
225 outbuffer
, buffer_length
- 1, &odone
, // Output.
226 &io_spec
, // Input, output and transfer spec.
227 NULL
, NULL
); // Default configuration.
230 int64_t soxr_execution_time
=
231 get_absolute_time_in_ns() - soxr_start_time
; // this must be zero or positive
232 int soxr_execution_time_int
= soxr_execution_time
; // must be in or around 1500000000
237 if (number_of_iterations
!= 0) {
238 config
.soxr_delay_index
= soxr_execution_time_int
/ number_of_iterations
;
240 debug(1, "No soxr-timing iterations performed, so \"basic\" iteration will be used.");
241 config
.soxr_delay_index
= 0; // used as a flag
243 debug(2, "soxr_delay: %d nanoseconds, soxr_delay_threshold: %d milliseconds.",
244 config
.soxr_delay_index
, config
.soxr_delay_threshold
/ 1000000);
245 if ((config
.packet_stuffing
== ST_soxr
) &&
246 (config
.soxr_delay_index
> config
.soxr_delay_threshold
))
247 inform("Note: this device may be too slow for \"soxr\" interpolation. Consider choosing the "
248 "\"basic\" or \"auto\" interpolation setting.");
249 if (config
.packet_stuffing
== ST_auto
)
251 1, "\"%s\" interpolation has been chosen.",
252 ((config
.soxr_delay_index
!= 0) && (config
.soxr_delay_index
<= config
.soxr_delay_threshold
))
260 void usage(char *progname
) {
262 #ifdef CONFIG_AIRPLAY_2
263 if (has_fltp_capable_aac_decoder() == 0) {
264 printf("\nIMPORTANT NOTE: Shairport Sync can not run on this system.\n");
265 printf("A Floating Planar (\"fltp\") AAC decoder is required, ");
266 printf("but the system's ffmpeg library does not seem to include one.\n");
268 "https://github.com/mikebrady/shairport-sync/blob/development/"
269 "TROUBLESHOOTING.md#aac-decoder-issues-airplay-2-only\n\n");
274 printf("Usage: %s [options...]\n", progname
);
275 printf(" or: %s [options...] -- [audio output-specific options]\n", progname
);
277 printf("Options:\n");
278 printf(" -h, --help show this help.\n");
279 #ifdef CONFIG_LIBDAEMON
280 printf(" -d, --daemon daemonise.\n");
281 printf(" -j, --justDaemoniseNoPIDFile daemonise without a PID file.\n");
282 printf(" -k, --kill kill the existing shairport daemon.\n");
284 printf(" -V, --version show version information.\n");
285 printf(" -c, --configfile=FILE read configuration settings from FILE. Default is "
286 "/etc/shairport-sync.conf.\n");
290 "The following general options are for backward compatibility. These and all new options "
291 "have settings in the configuration file, by default /etc/shairport-sync.conf:\n");
292 printf(" -v, --verbose -v print debug information; -vv more; -vvv lots.\n");
293 printf(" -p, --port=PORT set RTSP listening port.\n");
294 printf(" -a, --name=NAME set advertised name.\n");
296 " -L, --latency=FRAMES [Deprecated] Set the latency for audio sent from an unknown "
298 printf(" The default is to set it automatically.\n");
299 printf(" -S, --stuffing=MODE set how to adjust current latency to match desired latency, "
301 printf(" \"basic\" inserts or deletes audio frames from "
302 "packet frames with low processor overhead, and \n");
304 " \"soxr\" uses libsoxr to minimally resample packet frames -- "
305 "moderate processor overhead.\n");
306 printf(" \"auto\" (default) chooses basic or soxr depending on "
307 "processor capability.\n");
309 " \"soxr\" option only available if built with soxr support.\n");
310 printf(" -B, --on-start=PROGRAM run PROGRAM when playback is about to begin.\n");
311 printf(" -E, --on-stop=PROGRAM run PROGRAM when playback has ended.\n");
313 " For -B and -E options, specify the full path to the program, "
314 "e.g. /usr/bin/logger.\n");
315 printf(" Executable scripts work, but must have the appropriate "
317 "(#!/bin/sh) in the headline.\n");
319 " -w, --wait-cmd wait until the -B or -E programs finish before continuing.\n");
320 printf(" -o, --output=BACKEND select audio output method.\n");
321 printf(" -m, --mdns=BACKEND force the use of BACKEND to advertize the service.\n");
322 printf(" if no mdns provider is specified,\n");
323 printf(" shairport tries them all until one works.\n");
325 " -r, --resync=THRESHOLD [Deprecated] resync if error exceeds this number of frames. "
327 "stop resyncing.\n");
329 " -t, --timeout=SECONDS go back to idle mode from play mode after a break in "
330 "communications of this many seconds (default 120). Set to 0 never to exit play mode.\n");
331 printf(" --statistics print some interesting statistics -- output to the logfile "
332 "if running as a daemon.\n");
333 printf(" --tolerance=TOLERANCE [Deprecated] allow a synchronization error of TOLERANCE "
335 "88) before trying to correct it.\n");
336 printf(" --password=PASSWORD require PASSWORD to connect. Default is not to require a "
338 printf(" --logOutputLevel log the output level setting -- useful for setting maximum "
340 #ifdef CONFIG_METADATA
341 printf(" -M, --metadata-enable ask for metadata from the source and process it.\n");
342 printf(" --metadata-pipename=PIPE send metadata to PIPE, e.g. "
343 "--metadata-pipename=/tmp/%s-metadata.\n",
345 printf(" The default is /tmp/%s-metadata.\n", config
.appName
);
347 " -g, --get-coverart Include cover art in the metadata to be gathered and sent.\n");
349 printf(" --log-to-syslog send debug and statistics information through syslog\n");
351 " If used, this should be the first command line argument.\n");
352 printf(" -u, --use-stderr [Deprecated] This setting is not needed -- stderr is now "
353 "used by default.\n");
359 #ifdef CONFIG_AIRPLAY_2
364 int parse_options(int argc
, char **argv
) {
365 // there are potential memory leaks here -- it's called a second time, previously allocated
366 // strings will dangle.
367 char *raw_service_name
= NULL
; /* Used to pick up the service name before possibly expanding it */
368 char *stuffing
= NULL
; /* used for picking up the stuffing option */
369 signed char c
; /* used for argument parsing */
370 // int i = 0; /* used for tracking options */
371 int fResyncthreshold
= (int)(config
.resyncthreshold
* 44100);
372 int fTolerance
= (int)(config
.tolerance
* 44100);
373 poptContext optCon
; /* context for parsing command-line options */
374 struct poptOption optionsTable
[] = {
375 {"verbose", 'v', POPT_ARG_NONE
, NULL
, 'v', NULL
, NULL
},
376 {"kill", 'k', POPT_ARG_NONE
, &killOption
, 0, NULL
, NULL
},
377 {"daemon", 'd', POPT_ARG_NONE
, &daemonisewith
, 0, NULL
, NULL
},
378 {"justDaemoniseNoPIDFile", 'j', POPT_ARG_NONE
, &daemonisewithout
, 0, NULL
, NULL
},
379 {"configfile", 'c', POPT_ARG_STRING
, &config
.configfile
, 0, NULL
, NULL
},
380 {"statistics", 0, POPT_ARG_NONE
, &config
.statistics_requested
, 0, NULL
, NULL
},
381 {"logOutputLevel", 0, POPT_ARG_NONE
, &config
.logOutputLevel
, 0, NULL
, NULL
},
382 {"version", 'V', POPT_ARG_NONE
, NULL
, 0, NULL
, NULL
},
383 {"port", 'p', POPT_ARG_INT
, &config
.port
, 0, NULL
, NULL
},
384 {"name", 'a', POPT_ARG_STRING
, &raw_service_name
, 0, NULL
, NULL
},
385 {"output", 'o', POPT_ARG_STRING
, &config
.output_name
, 0, NULL
, NULL
},
386 {"on-start", 'B', POPT_ARG_STRING
, &config
.cmd_start
, 0, NULL
, NULL
},
387 {"on-stop", 'E', POPT_ARG_STRING
, &config
.cmd_stop
, 0, NULL
, NULL
},
388 {"wait-cmd", 'w', POPT_ARG_NONE
, &config
.cmd_blocking
, 0, NULL
, NULL
},
389 {"mdns", 'm', POPT_ARG_STRING
, &config
.mdns_name
, 0, NULL
, NULL
},
390 {"latency", 'L', POPT_ARG_INT
, &config
.userSuppliedLatency
, 0, NULL
, NULL
},
391 {"stuffing", 'S', POPT_ARG_STRING
, &stuffing
, 'S', NULL
, NULL
},
392 {"resync", 'r', POPT_ARG_INT
, &fResyncthreshold
, 0, NULL
, NULL
},
393 {"timeout", 't', POPT_ARG_INT
, &config
.timeout
, 't', NULL
, NULL
},
394 {"password", 0, POPT_ARG_STRING
, &config
.password
, 0, NULL
, NULL
},
395 {"tolerance", 'z', POPT_ARG_INT
, &fTolerance
, 0, NULL
, NULL
},
396 {"use-stderr", 'u', POPT_ARG_NONE
, NULL
, 'u', NULL
, NULL
},
397 {"log-to-syslog", 0, POPT_ARG_NONE
, &log_to_syslog_selected
, 0, NULL
, NULL
},
398 #ifdef CONFIG_METADATA
399 {"metadata-enable", 'M', POPT_ARG_NONE
, &config
.metadata_enabled
, 'M', NULL
, NULL
},
400 {"metadata-pipename", 0, POPT_ARG_STRING
, &config
.metadata_pipename
, 0, NULL
, NULL
},
401 {"get-coverart", 'g', POPT_ARG_NONE
, &config
.get_coverart
, 'g', NULL
, NULL
},
403 POPT_AUTOHELP
{NULL
, 0, 0, NULL
, 0, NULL
, NULL
}};
405 // we have to parse the command line arguments to look for a config file
409 for (j
= 0; j
< argc
; j
++)
410 if (strcmp(argv
[j
], "--") == 0)
413 optCon
= poptGetContext(NULL
, optind
, (const char **)argv
, optionsTable
, 0);
415 die("Can not get a secondary popt context.");
416 poptSetOtherOptionHelp(optCon
, "[OPTIONS]* ");
418 /* Now do options processing just to get a debug log destination and level */
420 while ((c
= poptGetNextOpt(optCon
)) >= 0) {
426 inform("Warning: the option -u is no longer needed and is deprecated. Debug and statistics "
427 "output to STDERR is now the default. Use \"--log-to-syslog\" to revert.");
430 inform("Warning: the option -D or --disconnectFromOutput is deprecated.");
433 inform("Warning: the option -R or --reconnectToOutput is deprecated.");
436 inform("Warning: the option -A or --AirPlayLatency is deprecated and ignored. This setting "
438 "automatically received from the AirPlay device.");
441 inform("Warning: the option -i or --iTunesLatency is deprecated and ignored. This setting is "
443 "automatically received from iTunes");
447 "Warning: the option --forkedDaapdLatency is deprecated and ignored. This setting is now "
448 "automatically received from forkedDaapd");
451 inform("Warning: the option -r or --resync is deprecated. Please use the "
452 "\"resync_threshold_in_seconds\" setting in the config file instead.");
455 inform("Warning: the option --tolerance is deprecated. Please use the "
456 "\"drift_tolerance_in_seconds\" setting in the config file instead.");
461 die("%s: %s", poptBadOption(optCon
, POPT_BADOPTION_NOALIAS
), poptStrerror(c
));
464 poptFreeContext(optCon
);
466 if (log_to_syslog_selected
) {
467 // if this was the first command line argument, it'll already have been chosen
468 if (log_to_syslog_select_is_first_command_line_argument
== 0) {
469 inform("Suggestion: make \"--log-to-syslog\" the first command line argument to ensure "
470 "messages go to the syslog right from the beginning.");
475 #ifdef CONFIG_LIBDAEMON
476 if ((daemonisewith
) && (daemonisewithout
))
477 die("Select either daemonize_with_pid_file or daemonize_without_pid_file -- you have selected "
479 if ((daemonisewith
) || (daemonisewithout
)) {
480 config
.daemonise
= 1;
482 config
.daemonise_store_pid
= 1;
486 config
.resyncthreshold
= 1.0 * fResyncthreshold
/ 44100;
487 config
.tolerance
= 1.0 * fTolerance
/ 44100;
488 config
.audio_backend_silent_lead_in_time_auto
=
489 1; // start outputting silence as soon as packets start arriving
490 config
.airplay_volume
= -24.0; // if no volume is ever set, default to initial default value if
491 // nothing else comes in first.
492 config
.fixedLatencyOffset
= 11025; // this sounds like it works properly.
493 config
.diagnostic_drop_packet_fraction
= 0.0;
494 config
.active_state_timeout
= 10.0;
495 config
.soxr_delay_threshold
= 30 * 1000000; // the soxr measurement time (nanoseconds) of two
496 // oneshots must not exceed this if soxr interpolation
497 // is to be chosen automatically.
498 config
.volume_range_hw_priority
=
499 0; // if combining software and hardware volume control, give the software priority
500 // i.e. when reducing volume, reduce the sw first before reducing the software.
501 // this is because some hw mixers mute at the bottom of their range, and they don't always
502 // advertise this fact
503 config
.resend_control_first_check_time
=
504 0.10; // wait this many seconds before requesting the resending of a missing packet
505 config
.resend_control_check_interval_time
=
506 0.25; // wait this many seconds before again requesting the resending of a missing packet
507 config
.resend_control_last_check_time
=
508 0.10; // give up if the packet is still missing this close to when it's needed
509 config
.missing_port_dacp_scan_interval_seconds
=
510 2.0; // check at this interval if no DACP port number is known
512 config
.minimum_free_buffer_headroom
= 125; // leave approximately one second's worth of buffers
513 // free after calculating the effective latency.
514 // e.g. if we have 1024 buffers or 352 frames = 8.17 seconds and we have a nominal latency of 2.0
515 // seconds then we can add an offset of 5.17 seconds and still leave a second's worth of buffers
516 // for unexpected circumstances
518 #ifdef CONFIG_METADATA
519 /* Get the metadata setting. */
520 config
.metadata_enabled
= 1; // if metadata support is included, then enable it by default
521 config
.get_coverart
= 1; // if metadata support is included, then enable it by default
524 #ifdef CONFIG_CONVOLUTION
525 config
.convolution_max_length
= 8192;
527 config
.loudness_reference_volume_db
= -20;
529 #ifdef CONFIG_METADATA_HUB
530 config
.cover_art_cache_dir
= "/tmp/shairport-sync/.cache/coverart";
531 config
.scan_interval_when_active
=
532 1; // number of seconds between DACP server scans when playing something
533 config
.scan_interval_when_inactive
=
534 1; // number of seconds between DACP server scans when playing nothing
535 config
.scan_max_bad_response_count
=
536 5; // number of successive bad results to ignore before giving up
537 // config.scan_max_inactive_count =
538 // (365 * 24 * 60 * 60) / config.scan_interval_when_inactive; // number of scans to do before
540 // not made active again (not used)
543 #ifdef CONFIG_AIRPLAY_2
544 // the features code is a 64-bit number, but in the mDNS advertisement, the least significant 32
545 // bit are given first for example, if the features number is 0x1C340405F4A00, it will be given as
546 // features=0x405F4A00,0x1C340 in the mDNS string, and in a signed decimal number in the plist:
547 // 496155702020608 this setting here is the source of both the plist features response and the
549 // note: 0x300401F4A00 works but with weird delays and stuff
550 // config.airplay_features = 0x1C340405FCA00;
552 ((uint64_t)1 << 17) | ((uint64_t)1 << 16) | ((uint64_t)1 << 15) | ((uint64_t)1 << 50);
553 config
.airplay_features
=
554 0x1C340405D4A00 & (~mask
); // APX + Authentication4 (b14) with no metadata (see below)
555 // Advertised with mDNS and returned with GET /info, see
556 // https://openairplay.github.io/airplay-spec/status_flags.html 0x4: Audio cable attached, no PIN
557 // required (transient pairing), 0x204: Audio cable attached, OneTimePairingRequired 0x604: Audio
558 // cable attached, OneTimePairingRequired, device was setup for Homekit access control
559 config
.airplay_statusflags
= 0x04;
560 // Set to NULL to work with transient pairing
561 config
.airplay_pin
= NULL
;
563 // use the start of the config.hw_addr and the PID to generate the default airplay_device_id
564 uint64_t temporary_airplay_id
= nctoh64(config
.hw_addr
);
565 temporary_airplay_id
=
566 temporary_airplay_id
>> 16; // we only use the first 6 bytes but have imported 8.
568 // now generate a UUID
569 // from https://stackoverflow.com/questions/51053568/generating-a-random-uuid-in-c
572 uuid_generate_random(binuuid
);
574 char *uuid
= malloc(UUID_STR_LEN
);
575 // Produces a UUID string at uuid consisting of lower-case letters
576 uuid_unparse_lower(binuuid
, uuid
);
577 config
.airplay_pi
= uuid
;
581 // config_setting_t *setting;
586 // debug(1, "Looking for the configuration file \"%s\".", config.configfile);
588 config_init(&config_file_stuff
);
590 char *config_file_real_path
= realpath(config
.configfile
, NULL
);
591 if (config_file_real_path
== NULL
) {
592 debug(2, "can't resolve the configuration file \"%s\".", config
.configfile
);
594 debug(2, "looking for configuration file at full path \"%s\"", config_file_real_path
);
595 /* Read the file. If there is an error, report it and exit. */
596 if (config_read_file(&config_file_stuff
, config_file_real_path
)) {
597 free(config_file_real_path
);
598 config_set_auto_convert(&config_file_stuff
,
599 1); // allow autoconversion from int/float to int/float
600 // make config.cfg point to it
601 config
.cfg
= &config_file_stuff
;
602 /* Get the Service Name. */
603 if (config_lookup_string(config
.cfg
, "general.name", &str
)) {
604 raw_service_name
= (char *)str
;
606 #ifdef CONFIG_LIBDAEMON
607 /* Get the Daemonize setting. */
608 config_set_lookup_bool(config
.cfg
, "sessioncontrol.daemonize_with_pid_file", &daemonisewith
);
610 /* Get the Just_Daemonize setting. */
611 config_set_lookup_bool(config
.cfg
, "sessioncontrol.daemonize_without_pid_file",
614 /* Get the directory path for the pid file created when the program is daemonised. */
615 if (config_lookup_string(config
.cfg
, "sessioncontrol.daemon_pid_dir", &str
))
616 config
.piddir
= (char *)str
;
619 /* Get the mdns_backend setting. */
620 if (config_lookup_string(config
.cfg
, "general.mdns_backend", &str
))
621 config
.mdns_name
= (char *)str
;
623 /* Get the output_backend setting. */
624 if (config_lookup_string(config
.cfg
, "general.output_backend", &str
))
625 config
.output_name
= (char *)str
;
627 /* Get the port setting. */
628 if (config_lookup_int(config
.cfg
, "general.port", &value
)) {
629 if ((value
< 0) || (value
> 65535))
630 #ifdef CONFIG_AIRPLAY_2
631 die("Invalid port number \"%sd\". It should be between 0 and 65535, default is 7000",
634 die("Invalid port number \"%sd\". It should be between 0 and 65535, default is 5000",
641 /* Get the udp port base setting. */
642 if (config_lookup_int(config
.cfg
, "general.udp_port_base", &value
)) {
643 if ((value
< 0) || (value
> 65535))
644 die("Invalid port number \"%sd\". It should be between 0 and 65535, default is 6001",
647 config
.udp_port_base
= value
;
650 /* Get the udp port range setting. This is number of ports that will be tried for free ports ,
651 * starting at the port base. Only three ports are needed. */
652 if (config_lookup_int(config
.cfg
, "general.udp_port_range", &value
)) {
653 if ((value
< 3) || (value
> 65535))
654 die("Invalid port range \"%sd\". It should be between 3 and 65535, default is 10",
657 config
.udp_port_range
= value
;
660 /* Get the password setting. */
661 if (config_lookup_string(config
.cfg
, "general.password", &str
))
662 config
.password
= (char *)str
;
664 if (config_lookup_string(config
.cfg
, "general.interpolation", &str
)) {
665 if (strcasecmp(str
, "basic") == 0)
666 config
.packet_stuffing
= ST_basic
;
667 else if (strcasecmp(str
, "auto") == 0)
668 config
.packet_stuffing
= ST_auto
;
669 else if (strcasecmp(str
, "soxr") == 0)
671 config
.packet_stuffing
= ST_soxr
;
673 warn("The soxr option not available because this version of shairport-sync was built "
675 "support. Change the \"general/interpolation\" setting in the configuration file.");
678 die("Invalid interpolation option choice \"%s\". It should be \"auto\", \"basic\" or "
685 /* Get the soxr_delay_threshold setting. */
686 /* Convert between the input, given in milliseconds, and the stored values in nanoseconds. */
687 if (config_lookup_int(config
.cfg
, "general.soxr_delay_threshold", &value
)) {
688 if ((value
>= 1) && (value
<= 100))
689 config
.soxr_delay_threshold
= value
* 1000000;
691 warn("Invalid general soxr_delay_threshold setting option choice \"%d\". It should be "
692 "between 1 and 100, "
693 "inclusive. Default is %d (milliseconds).",
694 value
, config
.soxr_delay_threshold
/ 1000000);
698 /* Get the statistics setting. */
699 if (config_set_lookup_bool(config
.cfg
, "general.statistics",
700 &(config
.statistics_requested
))) {
701 warn("The \"general\" \"statistics\" setting is deprecated. Please use the \"diagnostics\" "
702 "\"statistics\" setting instead.");
705 /* The old drift tolerance setting. */
706 if (config_lookup_int(config
.cfg
, "general.drift", &value
)) {
707 inform("The drift setting is deprecated. Use "
708 "drift_tolerance_in_seconds instead");
709 config
.tolerance
= 1.0 * value
/ 44100;
712 /* The old resync setting. */
713 if (config_lookup_int(config
.cfg
, "general.resync_threshold", &value
)) {
714 inform("The resync_threshold setting is deprecated. Use "
715 "resync_threshold_in_seconds instead");
716 config
.resyncthreshold
= 1.0 * value
/ 44100;
719 /* Get the drift tolerance setting. */
720 if (config_lookup_float(config
.cfg
, "general.drift_tolerance_in_seconds", &dvalue
))
721 config
.tolerance
= dvalue
;
723 /* Get the resync setting. */
724 if (config_lookup_float(config
.cfg
, "general.resync_threshold_in_seconds", &dvalue
))
725 config
.resyncthreshold
= dvalue
;
727 /* Get the verbosity setting. */
728 if (config_lookup_int(config
.cfg
, "general.log_verbosity", &value
)) {
729 warn("The \"general\" \"log_verbosity\" setting is deprecated. Please use the "
730 "\"diagnostics\" \"log_verbosity\" setting instead.");
731 if ((value
>= 0) && (value
<= 3))
734 die("Invalid log verbosity setting option choice \"%d\". It should be between 0 and 3, "
739 /* Get the verbosity setting. */
740 if (config_lookup_int(config
.cfg
, "diagnostics.log_verbosity", &value
)) {
741 if ((value
>= 0) && (value
<= 3))
744 die("Invalid diagnostics log_verbosity setting option choice \"%d\". It should be "
750 /* Get the config.debugger_show_file_and_line in debug messages setting. */
751 if (config_lookup_string(config
.cfg
, "diagnostics.log_show_file_and_line", &str
)) {
752 if (strcasecmp(str
, "no") == 0)
753 config
.debugger_show_file_and_line
= 0;
754 else if (strcasecmp(str
, "yes") == 0)
755 config
.debugger_show_file_and_line
= 1;
757 die("Invalid diagnostics log_show_file_and_line option choice \"%s\". It should be "
762 /* Get the show elapsed time in debug messages setting. */
763 if (config_lookup_string(config
.cfg
, "diagnostics.log_show_time_since_startup", &str
)) {
764 if (strcasecmp(str
, "no") == 0)
765 config
.debugger_show_elapsed_time
= 0;
766 else if (strcasecmp(str
, "yes") == 0)
767 config
.debugger_show_elapsed_time
= 1;
769 die("Invalid diagnostics log_show_time_since_startup option choice \"%s\". It should be "
774 /* Get the show relative time in debug messages setting. */
775 if (config_lookup_string(config
.cfg
, "diagnostics.log_show_time_since_last_message", &str
)) {
776 if (strcasecmp(str
, "no") == 0)
777 config
.debugger_show_relative_time
= 0;
778 else if (strcasecmp(str
, "yes") == 0)
779 config
.debugger_show_relative_time
= 1;
781 die("Invalid diagnostics log_show_time_since_last_message option choice \"%s\". It "
782 "should be \"yes\" or \"no\"",
786 /* Get the statistics setting. */
787 if (config_lookup_string(config
.cfg
, "diagnostics.statistics", &str
)) {
788 if (strcasecmp(str
, "no") == 0)
789 config
.statistics_requested
= 0;
790 else if (strcasecmp(str
, "yes") == 0)
791 config
.statistics_requested
= 1;
793 die("Invalid diagnostics statistics option choice \"%s\". It should be \"yes\" or "
798 /* Get the disable_resend_requests setting. */
799 if (config_lookup_string(config
.cfg
, "diagnostics.disable_resend_requests", &str
)) {
800 config
.disable_resend_requests
= 0; // this is for legacy -- only set by -t 0
801 if (strcasecmp(str
, "no") == 0)
802 config
.disable_resend_requests
= 0;
803 else if (strcasecmp(str
, "yes") == 0)
804 config
.disable_resend_requests
= 1;
806 die("Invalid diagnostic disable_resend_requests option choice \"%s\". It should be "
812 /* Get the drop packets setting. */
813 if (config_lookup_float(config
.cfg
, "diagnostics.drop_this_fraction_of_audio_packets",
815 if ((dvalue
>= 0.0) && (dvalue
<= 3.0))
816 config
.diagnostic_drop_packet_fraction
= dvalue
;
818 die("Invalid diagnostics drop_this_fraction_of_audio_packets setting \"%d\". It should "
820 "between 0.0 and 1.0, "
825 /* Get the diagnostics output default. */
826 if (config_lookup_string(config
.cfg
, "diagnostics.log_output_to", &str
)) {
827 if (strcasecmp(str
, "syslog") == 0)
829 else if (strcasecmp(str
, "stdout") == 0) {
831 } else if (strcasecmp(str
, "stderr") == 0) {
834 config
.log_file_path
= (char *)str
;
839 /* Get the ignore_volume_control setting. */
840 if (config_lookup_string(config
.cfg
, "general.ignore_volume_control", &str
)) {
841 if (strcasecmp(str
, "no") == 0)
842 config
.ignore_volume_control
= 0;
843 else if (strcasecmp(str
, "yes") == 0)
844 config
.ignore_volume_control
= 1;
846 die("Invalid ignore_volume_control option choice \"%s\". It should be \"yes\" or \"no\"",
850 /* Get the optional volume_max_db setting. */
851 if (config_lookup_float(config
.cfg
, "general.volume_max_db", &dvalue
)) {
852 // debug(1, "Max volume setting of %f dB", dvalue);
853 config
.volume_max_db
= dvalue
;
854 config
.volume_max_db_set
= 1;
857 if (config_lookup_string(config
.cfg
, "general.run_this_when_volume_is_set", &str
)) {
858 config
.cmd_set_volume
= (char *)str
;
861 /* Get the playback_mode setting */
862 if (config_lookup_string(config
.cfg
, "general.playback_mode", &str
)) {
863 if (strcasecmp(str
, "stereo") == 0)
864 config
.playback_mode
= ST_stereo
;
865 else if (strcasecmp(str
, "mono") == 0)
866 config
.playback_mode
= ST_mono
;
867 else if (strcasecmp(str
, "reverse stereo") == 0)
868 config
.playback_mode
= ST_reverse_stereo
;
869 else if (strcasecmp(str
, "both left") == 0)
870 config
.playback_mode
= ST_left_only
;
871 else if (strcasecmp(str
, "both right") == 0)
872 config
.playback_mode
= ST_right_only
;
874 die("Invalid playback_mode choice \"%s\". It should be \"stereo\" (default), \"mono\", "
875 "\"reverse stereo\", \"both left\", \"both right\"",
879 /* Get the volume control profile setting -- "standard" or "flat" */
880 if (config_lookup_string(config
.cfg
, "general.volume_control_profile", &str
)) {
881 if (strcasecmp(str
, "standard") == 0)
882 config
.volume_control_profile
= VCP_standard
;
883 else if (strcasecmp(str
, "flat") == 0)
884 config
.volume_control_profile
= VCP_flat
;
886 die("Invalid volume_control_profile choice \"%s\". It should be \"standard\" (default) "
891 config_set_lookup_bool(config
.cfg
, "general.volume_control_combined_hardware_priority",
892 &config
.volume_range_hw_priority
);
894 /* Get the interface to listen on, if specified Default is all interfaces */
895 /* we keep the interface name and the index */
897 if (config_lookup_string(config
.cfg
, "general.interface", &str
))
898 config
.interface
= strdup(str
);
900 if (config_lookup_string(config
.cfg
, "general.interface", &str
)) {
902 config
.interface_index
= if_nametoindex(config
.interface
);
904 if (config
.interface_index
== 0) {
906 "The mdns service interface \"%s\" was not found, so the setting has been ignored.",
908 free(config
.interface
);
909 config
.interface
= NULL
;
913 /* Get the regtype -- the service type and protocol, separated by a dot. Default is
915 if (config_lookup_string(config
.cfg
, "general.regtype", &str
))
916 config
.regtype
= strdup(str
);
918 /* Get the volume range, in dB, that should be used If not set, it means you just use the
919 * range set by the mixer. */
920 if (config_lookup_int(config
.cfg
, "general.volume_range_db", &value
)) {
921 if ((value
< 30) || (value
> 150))
922 die("Invalid volume range %d dB. It should be between 30 and 150 dB. Zero means use "
923 "the mixer's native range. The setting reamins at %d.",
924 value
, config
.volume_range_db
);
926 config
.volume_range_db
= value
;
929 /* Get the alac_decoder setting. */
930 if (config_lookup_string(config
.cfg
, "general.alac_decoder", &str
)) {
931 if (strcasecmp(str
, "hammerton") == 0)
932 config
.use_apple_decoder
= 0;
933 else if (strcasecmp(str
, "apple") == 0) {
934 if ((config
.decoders_supported
& 1 << decoder_apple_alac
) != 0)
935 config
.use_apple_decoder
= 1;
937 inform("Support for the Apple ALAC decoder has not been compiled into this version of "
938 "Shairport Sync. The default decoder will be used.");
940 die("Invalid alac_decoder option choice \"%s\". It should be \"hammerton\" or \"apple\"",
944 /* Get the resend control settings. */
945 if (config_lookup_float(config
.cfg
, "general.resend_control_first_check_time", &dvalue
)) {
946 if ((dvalue
>= 0.0) && (dvalue
<= 3.0))
947 config
.resend_control_first_check_time
= dvalue
;
949 warn("Invalid general resend_control_first_check_time setting \"%f\". It should "
951 "between 0.0 and 3.0, "
952 "inclusive. The setting remains at %f seconds.",
953 dvalue
, config
.resend_control_first_check_time
);
956 if (config_lookup_float(config
.cfg
, "general.resend_control_check_interval_time", &dvalue
)) {
957 if ((dvalue
>= 0.0) && (dvalue
<= 3.0))
958 config
.resend_control_check_interval_time
= dvalue
;
960 warn("Invalid general resend_control_check_interval_time setting \"%f\". It should "
962 "between 0.0 and 3.0, "
963 "inclusive. The setting remains at %f seconds.",
964 dvalue
, config
.resend_control_check_interval_time
);
967 if (config_lookup_float(config
.cfg
, "general.resend_control_last_check_time", &dvalue
)) {
968 if ((dvalue
>= 0.0) && (dvalue
<= 3.0))
969 config
.resend_control_last_check_time
= dvalue
;
971 warn("Invalid general resend_control_last_check_time setting \"%f\". It should "
973 "between 0.0 and 3.0, "
974 "inclusive. The setting remains at %f seconds.",
975 dvalue
, config
.resend_control_last_check_time
);
978 if (config_lookup_float(config
.cfg
, "general.missing_port_dacp_scan_interval_seconds",
980 if ((dvalue
>= 0.0) && (dvalue
<= 300.0))
981 config
.missing_port_dacp_scan_interval_seconds
= dvalue
;
983 warn("Invalid general missing_port_dacp_scan_interval_seconds setting \"%f\". It should "
985 "between 0.0 and 300.0, "
986 "inclusive. The setting remains at %f seconds.",
987 dvalue
, config
.missing_port_dacp_scan_interval_seconds
);
990 /* Get the default latency. Deprecated! */
991 if (config_lookup_int(config
.cfg
, "latencies.default", &value
))
992 config
.userSuppliedLatency
= value
;
994 #ifdef CONFIG_METADATA
995 /* Get the metadata setting. */
996 if (config_lookup_string(config
.cfg
, "metadata.enabled", &str
)) {
997 if (strcasecmp(str
, "no") == 0)
998 config
.metadata_enabled
= 0;
999 else if (strcasecmp(str
, "yes") == 0)
1000 config
.metadata_enabled
= 1;
1002 die("Invalid metadata enabled option choice \"%s\". It should be \"yes\" or \"no\"", str
);
1005 if (config_lookup_string(config
.cfg
, "metadata.include_cover_art", &str
)) {
1006 if (strcasecmp(str
, "no") == 0)
1007 config
.get_coverart
= 0;
1008 else if (strcasecmp(str
, "yes") == 0)
1009 config
.get_coverart
= 1;
1011 die("Invalid metadata include_cover_art option choice \"%s\". It should be \"yes\" or "
1016 if (config_lookup_string(config
.cfg
, "metadata.pipe_name", &str
)) {
1017 config
.metadata_pipename
= (char *)str
;
1020 if (config_lookup_string(config
.cfg
, "metadata.socket_address", &str
)) {
1021 config
.metadata_sockaddr
= (char *)str
;
1023 if (config_lookup_int(config
.cfg
, "metadata.socket_port", &value
)) {
1024 config
.metadata_sockport
= value
;
1026 config
.metadata_sockmsglength
= 500;
1027 if (config_lookup_int(config
.cfg
, "metadata.socket_msglength", &value
)) {
1028 config
.metadata_sockmsglength
= value
< 500 ? 500 : value
> 65000 ? 65000 : value
;
1033 #ifdef CONFIG_METADATA_HUB
1034 if (config_lookup_string(config
.cfg
, "metadata.cover_art_cache_directory", &str
)) {
1035 config
.cover_art_cache_dir
= (char *)str
;
1038 if (config_lookup_string(config
.cfg
, "diagnostics.retain_cover_art", &str
)) {
1039 if (strcasecmp(str
, "no") == 0)
1040 config
.retain_coverart
= 0;
1041 else if (strcasecmp(str
, "yes") == 0)
1042 config
.retain_coverart
= 1;
1044 die("Invalid metadata \"retain_cover_art\" option choice \"%s\". It should be \"yes\" or "
1050 if (config_lookup_string(config
.cfg
, "sessioncontrol.run_this_before_play_begins", &str
)) {
1051 config
.cmd_start
= (char *)str
;
1054 if (config_lookup_string(config
.cfg
, "sessioncontrol.run_this_after_play_ends", &str
)) {
1055 config
.cmd_stop
= (char *)str
;
1058 if (config_lookup_string(config
.cfg
, "sessioncontrol.run_this_before_entering_active_state",
1060 config
.cmd_active_start
= (char *)str
;
1063 if (config_lookup_string(config
.cfg
, "sessioncontrol.run_this_after_exiting_active_state",
1065 config
.cmd_active_stop
= (char *)str
;
1068 if (config_lookup_float(config
.cfg
, "sessioncontrol.active_state_timeout", &dvalue
)) {
1070 warn("Invalid value \"%f\" for \"active_state_timeout\". It must be positive. "
1071 "The default of %f will be used instead.",
1072 dvalue
, config
.active_state_timeout
);
1074 config
.active_state_timeout
= dvalue
;
1077 if (config_lookup_string(config
.cfg
,
1078 "sessioncontrol.run_this_if_an_unfixable_error_is_detected", &str
)) {
1079 config
.cmd_unfixable
= (char *)str
;
1082 if (config_lookup_string(config
.cfg
, "sessioncontrol.wait_for_completion", &str
)) {
1083 if (strcasecmp(str
, "no") == 0)
1084 config
.cmd_blocking
= 0;
1085 else if (strcasecmp(str
, "yes") == 0)
1086 config
.cmd_blocking
= 1;
1088 warn("Invalid \"wait_for_completion\" option choice \"%s\". It should be "
1089 "\"yes\" or \"no\". It is set to \"no\".",
1093 if (config_lookup_string(config
.cfg
, "sessioncontrol.before_play_begins_returns_output",
1095 if (strcasecmp(str
, "no") == 0)
1096 config
.cmd_start_returns_output
= 0;
1097 else if (strcasecmp(str
, "yes") == 0)
1098 config
.cmd_start_returns_output
= 1;
1100 die("Invalid \"before_play_begins_returns_output\" option choice \"%s\". It "
1102 "\"yes\" or \"no\"",
1106 if (config_lookup_string(config
.cfg
, "sessioncontrol.allow_session_interruption", &str
)) {
1107 config
.dont_check_timeout
= 0; // this is for legacy -- only set by -t 0
1108 if (strcasecmp(str
, "no") == 0)
1109 config
.allow_session_interruption
= 0;
1110 else if (strcasecmp(str
, "yes") == 0)
1111 config
.allow_session_interruption
= 1;
1113 die("Invalid \"allow_interruption\" option choice \"%s\". It should be "
1119 if (config_lookup_int(config
.cfg
, "sessioncontrol.session_timeout", &value
)) {
1120 config
.timeout
= value
;
1121 config
.dont_check_timeout
= 0; // this is for legacy -- only set by -t 0
1124 #ifdef CONFIG_CONVOLUTION
1125 if (config_lookup_string(config
.cfg
, "dsp.convolution", &str
)) {
1126 if (strcasecmp(str
, "no") == 0)
1127 config
.convolution
= 0;
1128 else if (strcasecmp(str
, "yes") == 0)
1129 config
.convolution
= 1;
1131 die("Invalid dsp.convolution setting \"%s\". It should be \"yes\" or \"no\"", str
);
1134 if (config_lookup_float(config
.cfg
, "dsp.convolution_gain", &dvalue
)) {
1135 config
.convolution_gain
= dvalue
;
1136 if (dvalue
> 10 || dvalue
< -50)
1137 die("Invalid value \"%f\" for dsp.convolution_gain. It should be between -50 and +10 dB",
1141 if (config_lookup_int(config
.cfg
, "dsp.convolution_max_length", &value
)) {
1142 config
.convolution_max_length
= value
;
1144 if (value
< 1 || value
> 200000)
1145 die("dsp.convolution_max_length must be within 1 and 200000");
1148 if (config_lookup_string(config
.cfg
, "dsp.convolution_ir_file", &str
)) {
1149 config
.convolution_ir_file
= strdup(str
);
1150 config
.convolver_valid
=
1151 convolver_init(config
.convolution_ir_file
, config
.convolution_max_length
);
1154 if (config
.convolution
&& config
.convolution_ir_file
== NULL
) {
1155 warn("Convolution enabled but no convolution_ir_file provided");
1158 if (config_lookup_string(config
.cfg
, "dsp.loudness", &str
)) {
1159 if (strcasecmp(str
, "no") == 0)
1160 config
.loudness
= 0;
1161 else if (strcasecmp(str
, "yes") == 0)
1162 config
.loudness
= 1;
1164 die("Invalid dsp.loudness \"%s\". It should be \"yes\" or \"no\"", str
);
1167 if (config_lookup_float(config
.cfg
, "dsp.loudness_reference_volume_db", &dvalue
)) {
1168 config
.loudness_reference_volume_db
= dvalue
;
1169 if (dvalue
> 0 || dvalue
< -100)
1170 die("Invalid value \"%f\" for dsp.loudness_reference_volume_db. It should be between "
1175 if (config
.loudness
== 1 && config_lookup_string(config
.cfg
, "alsa.mixer_control_name", &str
))
1176 die("Loudness activated but hardware volume is active. You must remove "
1177 "\"alsa.mixer_control_name\" to use the loudness filter.");
1180 if (config_error_type(&config_file_stuff
) == CONFIG_ERR_FILE_IO
)
1181 debug(2, "Error reading configuration file \"%s\": \"%s\".",
1182 config_error_file(&config_file_stuff
), config_error_text(&config_file_stuff
));
1184 die("Line %d of the configuration file \"%s\":\n%s", config_error_line(&config_file_stuff
),
1185 config_error_file(&config_file_stuff
), config_error_text(&config_file_stuff
));
1188 #if defined(CONFIG_DBUS_INTERFACE)
1189 /* Get the dbus service sbus setting. */
1190 if (config_lookup_string(config
.cfg
, "general.dbus_service_bus", &str
)) {
1191 if (strcasecmp(str
, "system") == 0)
1192 config
.dbus_service_bus_type
= DBT_system
;
1193 else if (strcasecmp(str
, "session") == 0)
1194 config
.dbus_service_bus_type
= DBT_session
;
1196 die("Invalid dbus_service_bus option choice \"%s\". It should be \"system\" (default) or "
1202 #if defined(CONFIG_MPRIS_INTERFACE)
1203 /* Get the mpris service sbus setting. */
1204 if (config_lookup_string(config
.cfg
, "general.mpris_service_bus", &str
)) {
1205 if (strcasecmp(str
, "system") == 0)
1206 config
.mpris_service_bus_type
= DBT_system
;
1207 else if (strcasecmp(str
, "session") == 0)
1208 config
.mpris_service_bus_type
= DBT_session
;
1210 die("Invalid mpris_service_bus option choice \"%s\". It should be \"system\" (default) or "
1217 config_set_lookup_bool(config
.cfg
, "mqtt.enabled", &config
.mqtt_enabled
);
1218 if (config
.mqtt_enabled
&& !config
.metadata_enabled
) {
1219 die("You need to have metadata enabled in order to use mqtt");
1221 if (config_lookup_string(config
.cfg
, "mqtt.hostname", &str
)) {
1222 config
.mqtt_hostname
= (char *)str
;
1223 // TODO: Document that, if this is false, whole mqtt func is disabled
1225 config
.mqtt_port
= 1883;
1226 if (config_lookup_int(config
.cfg
, "mqtt.port", &value
)) {
1227 if ((value
< 0) || (value
> 65535))
1228 die("Invalid mqtt port number \"%sd\". It should be between 0 and 65535, default is 1883",
1231 config
.mqtt_port
= value
;
1234 if (config_lookup_string(config
.cfg
, "mqtt.username", &str
)) {
1235 config
.mqtt_username
= (char *)str
;
1237 if (config_lookup_string(config
.cfg
, "mqtt.password", &str
)) {
1238 config
.mqtt_password
= (char *)str
;
1241 if (config_lookup_string(config
.cfg
, "mqtt.capath", &str
)) {
1242 config
.mqtt_capath
= (char *)str
;
1245 if (config_lookup_string(config
.cfg
, "mqtt.cafile", &str
)) {
1247 die("Supply either mqtt cafile or mqtt capath -- you have supplied both!");
1248 config
.mqtt_cafile
= (char *)str
;
1251 if (config_lookup_string(config
.cfg
, "mqtt.certfile", &str
)) {
1252 config
.mqtt_certfile
= (char *)str
;
1255 if (config_lookup_string(config
.cfg
, "mqtt.keyfile", &str
)) {
1256 config
.mqtt_keyfile
= (char *)str
;
1259 if (certkeynum
!= 0 && certkeynum
!= 2) {
1260 die("If you want to use TLS Client Authentication, you have to specify "
1261 "mqtt.certfile AND mqtt.keyfile.\nYou have supplied only one of them.\n"
1262 "If you do not want to use TLS Client Authentication, leave both empty.");
1265 if (config_lookup_string(config
.cfg
, "mqtt.topic", &str
)) {
1266 config
.mqtt_topic
= (char *)str
;
1268 config_set_lookup_bool(config
.cfg
, "mqtt.publish_raw", &config
.mqtt_publish_raw
);
1269 config_set_lookup_bool(config
.cfg
, "mqtt.publish_parsed", &config
.mqtt_publish_parsed
);
1270 config_set_lookup_bool(config
.cfg
, "mqtt.publish_cover", &config
.mqtt_publish_cover
);
1271 if (config
.mqtt_publish_cover
&& !config
.get_coverart
) {
1272 die("You need to have metadata.include_cover_art enabled in order to use mqtt.publish_cover");
1274 config_set_lookup_bool(config
.cfg
, "mqtt.enable_remote", &config
.mqtt_enable_remote
);
1275 if (config_lookup_string(config
.cfg
, "mqtt.empty_payload_substitute", &str
)) {
1276 if (strlen(str
) == 0)
1277 config
.mqtt_empty_payload_substitute
= NULL
;
1279 config
.mqtt_empty_payload_substitute
= strdup(str
);
1281 config
.mqtt_empty_payload_substitute
= strdup("--");
1283 #ifndef CONFIG_AVAHI
1284 if (config
.mqtt_enable_remote
) {
1285 die("You have enabled MQTT remote control which requires shairport-sync to be built with "
1286 "Avahi, but your installation is not using avahi. Please reinstall/recompile with "
1287 "avahi enabled, or disable remote control.");
1292 #ifdef CONFIG_AIRPLAY_2
1295 // replace the airplay_device_id with this, if provided
1296 if (config_lookup_int64(config
.cfg
, "general.airplay_device_id", &aid
)) {
1297 temporary_airplay_id
= aid
;
1300 // add the airplay_device_id_offset if provided
1301 if (config_lookup_int64(config
.cfg
, "general.airplay_device_id_offset", &aid
)) {
1302 temporary_airplay_id
+= aid
;
1308 // now, do the command line options again, but this time do them fully -- it's a unix convention
1309 // that command line
1310 // arguments have precedence over configuration file settings.
1313 for (j
= 0; j
< argc
; j
++)
1314 if (strcmp(argv
[j
], "--") == 0)
1317 optCon
= poptGetContext(NULL
, optind
, (const char **)argv
, optionsTable
, 0);
1319 die("Can not get a popt context.");
1320 poptSetOtherOptionHelp(optCon
, "[OPTIONS]* ");
1322 /* Now do options processing, get portname */
1324 while ((c
= poptGetNextOpt(optCon
)) >= 0) {
1330 if (config
.timeout
== 0) {
1331 config
.dont_check_timeout
= 1;
1332 config
.allow_session_interruption
= 1;
1334 config
.dont_check_timeout
= 0;
1335 config
.allow_session_interruption
= 0;
1338 #ifdef CONFIG_METADATA
1340 config
.metadata_enabled
= 1;
1343 if (config
.metadata_enabled
== 0)
1344 die("If you want to get cover art, ensure metadata_enabled is true.");
1348 if (strcmp(stuffing
, "basic") == 0)
1349 config
.packet_stuffing
= ST_basic
;
1350 else if (strcmp(stuffing
, "auto") == 0)
1351 config
.packet_stuffing
= ST_auto
;
1352 else if (strcmp(stuffing
, "soxr") == 0)
1354 config
.packet_stuffing
= ST_soxr
;
1356 die("The soxr option not available because this version of shairport-sync was built "
1358 "support. Change the -S option setting.");
1361 die("Illegal stuffing option \"%s\" -- must be \"basic\" or \"soxr\"", stuffing
);
1366 die("%s: %s", poptBadOption(optCon
, POPT_BADOPTION_NOALIAS
), poptStrerror(c
));
1369 poptFreeContext(optCon
);
1371 // here, we are finally finished reading the options
1373 // finish the Airplay 2 options
1375 #ifdef CONFIG_AIRPLAY_2
1377 char shared_memory_interface_name
[256] = "";
1378 snprintf(shared_memory_interface_name
, sizeof(shared_memory_interface_name
), "/%s-%" PRIx64
"",
1379 config
.appName
, temporary_airplay_id
);
1380 // debug(1, "smi name: \"%s\"", shared_memory_interface_name);
1382 config
.nqptp_shared_memory_interface_name
= strdup(shared_memory_interface_name
);
1384 char apids
[6 * 2 + 5 + 1]; // six pairs of digits, 5 colons and a NUL
1385 apids
[6 * 2 + 5] = 0; // NUL termination
1387 char hexchar
[] = "0123456789abcdef";
1388 for (i
= 5; i
>= 0; i
--) {
1389 apids
[i
* 3 + 1] = hexchar
[temporary_airplay_id
& 0xF];
1390 temporary_airplay_id
= temporary_airplay_id
>> 4;
1391 apids
[i
* 3] = hexchar
[temporary_airplay_id
& 0xF];
1392 temporary_airplay_id
= temporary_airplay_id
>> 4;
1394 apids
[i
* 3 - 1] = ':';
1397 config
.airplay_device_id
= strdup(apids
);
1399 #ifdef CONFIG_METADATA
1400 // If we are asking for metadata, turn on the relevant bits
1401 if (config
.metadata_enabled
!= 0) {
1402 config
.airplay_features
|= (1 << 17) | (1 << 16); // 16 is progress, 17 is text
1403 // If we are asking for artwork, turn on the relevant bit
1404 if (config
.get_coverart
)
1405 config
.airplay_features
|= (1 << 15); // 15 is artwork
1411 #ifdef CONFIG_LIBDAEMON
1412 if ((daemonisewith
) && (daemonisewithout
))
1413 die("Select either daemonize_with_pid_file or daemonize_without_pid_file -- you have selected "
1415 if ((daemonisewith
) || (daemonisewithout
)) {
1416 config
.daemonise
= 1;
1418 config
.daemonise_store_pid
= 1;
1421 /* Check if we are called with -d or --daemon or -j or justDaemoniseNoPIDFile options*/
1422 if ((daemonisewith
!= 0) || (daemonisewithout
!= 0)) {
1424 "%s was built without libdaemon, so does not support daemonisation using the "
1425 "-d, --daemon, -j or --justDaemoniseNoPIDFile options\n",
1432 #ifdef CONFIG_METADATA
1433 if ((config
.metadata_enabled
== 1) && (config
.metadata_pipename
== NULL
)) {
1434 char temp_metadata_pipe_name
[4096];
1435 strcpy(temp_metadata_pipe_name
, "/tmp/");
1436 strcat(temp_metadata_pipe_name
, config
.appName
);
1437 strcat(temp_metadata_pipe_name
, "-metadata");
1438 config
.metadata_pipename
= strdup(temp_metadata_pipe_name
);
1439 debug(2, "default metadata_pipename is \"%s\".", temp_metadata_pipe_name
);
1443 /* if the regtype hasn't been set, do it now */
1444 if (config
.regtype
== NULL
)
1445 config
.regtype
= strdup("_raop._tcp");
1446 #ifdef CONFIG_AIRPLAY_2
1447 if (config
.regtype2
== NULL
)
1448 config
.regtype2
= strdup("_airplay._tcp");
1452 debuglev
= tdebuglev
;
1454 // now, do the substitutions in the service name
1456 gethostname(hostname
, 100);
1458 // strip off a terminating .<anything>, e.g. .local from the hostname
1459 char *last_dot
= strrchr(hostname
,'.');
1460 if (last_dot
!= NULL
)
1464 if (raw_service_name
== NULL
)
1465 i0
= strdup("%H"); // this is the default it the Service Name wasn't specified
1467 i0
= strdup(raw_service_name
);
1469 // here, do the substitutions for %h, %H, %v and %V
1470 char *i1
= str_replace(i0
, "%h", hostname
);
1471 if ((hostname
[0] >= 'a') && (hostname
[0] <= 'z'))
1472 hostname
[0] = hostname
[0] - 0x20; // convert a lowercase first letter into a capital letter
1473 char *i2
= str_replace(i1
, "%H", hostname
);
1474 char *i3
= str_replace(i2
, "%v", PACKAGE_VERSION
);
1475 char *vs
= get_version_string();
1476 config
.service_name
= str_replace(i3
, "%V", vs
); // service name complete
1484 // mqtt topic was not set. As we have the service name just now, set it
1485 if (config
.mqtt_topic
== NULL
) {
1486 int topic_length
= 1 + strlen(config
.service_name
) + 1;
1487 char *topic
= malloc(topic_length
+ 1);
1488 snprintf(topic
, topic_length
, "/%s/", config
.service_name
);
1489 config
.mqtt_topic
= topic
;
1493 #ifdef CONFIG_LIBDAEMON
1495 // now, check and calculate the pid directory
1496 #ifdef DEFINED_CUSTOM_PID_DIR
1497 char *use_this_pid_dir
= PIDDIR
;
1499 char temp_pid_dir
[4096];
1500 strcpy(temp_pid_dir
, "/var/run/");
1501 strcat(temp_pid_dir
, config
.appName
);
1502 debug(1, "default pid filename is \"%s\".", temp_pid_dir
);
1503 char *use_this_pid_dir
= temp_pid_dir
;
1505 // debug(1,"config.piddir \"%s\".",config.piddir);
1507 use_this_pid_dir
= config
.piddir
;
1508 if (use_this_pid_dir
)
1509 config
.computed_piddir
= strdup(use_this_pid_dir
);
1514 #if defined(CONFIG_DBUS_INTERFACE) || defined(CONFIG_MPRIS_INTERFACE)
1515 static GMainLoop
*g_main_loop
= NULL
;
1517 pthread_t dbus_thread
;
1518 void *dbus_thread_func(__attribute__((unused
)) void *arg
) {
1519 g_main_loop
= g_main_loop_new(NULL
, FALSE
);
1520 g_main_loop_run(g_main_loop
);
1521 debug(2, "g_main_loop thread exit");
1526 #ifdef CONFIG_LIBDAEMON
1527 char pid_file_path_string
[4096] = "\0";
1529 const char *pid_file_proc(void) {
1530 snprintf(pid_file_path_string
, sizeof(pid_file_path_string
), "%s/%s.pid", config
.computed_piddir
,
1531 daemon_pid_file_ident
? daemon_pid_file_ident
: "unknown");
1532 // debug(1,"pid_file_path_string \"%s\".",pid_file_path_string);
1533 return pid_file_path_string
;
1537 void exit_rtsp_listener() {
1538 pthread_cancel(rtsp_listener_thread
);
1539 pthread_join(rtsp_listener_thread
, NULL
); // not sure you need this
1542 void exit_function() {
1544 if (emergency_exit
== 0) {
1545 // the following is to ensure that if libdaemon has been included
1546 // that most of this code will be skipped when the parent process is exiting
1548 #ifdef CONFIG_LIBDAEMON
1549 if ((this_is_the_daemon_process
) ||
1550 (config
.daemonise
== 0)) { // if this is the daemon process that is exiting or it's not
1551 // actually daemonised at all
1553 debug(2, "exit function called...");
1555 Actually, there is no terminate_mqtt() function.
1557 if (config.mqtt_enabled) {
1563 #if defined(CONFIG_DBUS_INTERFACE) || defined(CONFIG_MPRIS_INTERFACE)
1565 Actually, there is no stop_mpris_service() function.
1566 #ifdef CONFIG_MPRIS_INTERFACE
1567 stop_mpris_service();
1570 #ifdef CONFIG_DBUS_INTERFACE
1571 debug(2, "Stopping D-Bus service");
1572 stop_dbus_service();
1575 debug(2, "Stopping D-Bus Loop Thread");
1576 g_main_loop_quit(g_main_loop
);
1577 pthread_join(dbus_thread
, NULL
);
1581 #ifdef CONFIG_DACP_CLIENT
1582 debug(2, "Stopping DACP Monitor");
1583 dacp_monitor_stop();
1586 #ifdef CONFIG_METADATA_HUB
1587 debug(2, "Stopping metadata hub");
1588 metadata_hub_stop();
1591 #ifdef CONFIG_METADATA
1592 debug(2, "Stopping metadata");
1593 metadata_stop(); // close down the metadata pipe
1595 debug(2, "Stopping the activity monitor.");
1596 activity_monitor_stop(0);
1598 if ((config
.output
) && (config
.output
->deinit
)) {
1599 debug(2, "Deinitialise the audio backend.");
1600 config
.output
->deinit();
1604 // be careful -- not sure if the thread can be cancelled cleanly, so wait for it to shut down
1605 debug(2, "Waiting for SoXr timecheck to terminate...");
1606 pthread_join(soxr_time_check_thread
, NULL
);
1610 free(conns
); // make sure the connections have been deleted first
1612 if (config
.service_name
)
1613 free(config
.service_name
);
1616 if (config
.mqtt_empty_payload_substitute
)
1617 free(config
.mqtt_empty_payload_substitute
);
1620 #ifdef CONFIG_CONVOLUTION
1621 if (config
.convolution_ir_file
)
1622 free(config
.convolution_ir_file
);
1626 free(config
.regtype
);
1627 #ifdef CONFIG_AIRPLAY_2
1628 if (config
.regtype2
)
1629 free(config
.regtype2
);
1630 if (config
.nqptp_shared_memory_interface_name
)
1631 free(config
.nqptp_shared_memory_interface_name
);
1632 if (config
.airplay_device_id
)
1633 free(config
.airplay_device_id
);
1634 if (config
.airplay_pin
)
1635 free(config
.airplay_pin
);
1636 if (config
.airplay_pi
)
1637 free(config
.airplay_pi
);
1638 ptp_shm_interface_close(); // close it if it's open
1641 #ifdef CONFIG_LIBDAEMON
1642 if (this_is_the_daemon_process
) {
1643 daemon_retval_send(0);
1644 daemon_pid_file_remove();
1645 daemon_signal_done();
1646 if (config
.computed_piddir
)
1647 free(config
.computed_piddir
);
1653 config_destroy(config
.cfg
);
1655 free(config
.appName
);
1657 // probably should be freeing malloc'ed memory here, including strdup-created strings...
1659 #ifdef CONFIG_LIBDAEMON
1660 if (this_is_the_daemon_process
) { // this is the daemon that is exiting
1661 debug(1, "libdaemon daemon exit");
1663 if (config
.daemonise
)
1664 debug(1, "libdaemon parent exit");
1666 debug(1, "exit_function libdaemon exit");
1669 mdns_unregister(); // once the dacp handler is done and all player threrads are done it should
1671 debug(1, "normal exit");
1674 debug(1, "emergency exit");
1678 // for removing zombie script processes
1679 // see: http://www.microhowto.info/howto/reap_zombie_processes_using_a_sigchld_handler.html
1680 // used with thanks.
1682 void handle_sigchld(__attribute__((unused
)) int sig
) {
1683 int saved_errno
= errno
;
1684 while (waitpid((pid_t
)(-1), 0, WNOHANG
) > 0) {
1686 errno
= saved_errno
;
1690 void intHandler(__attribute__((unused
)) int k
) {
1691 debug(2, "exit on SIGINT");
1695 void termHandler(__attribute__((unused
)) int k
) {
1696 debug(2, "exit on SIGTERM");
1700 int main(int argc
, char **argv
) {
1701 memset(&config
, 0, sizeof(config
)); // also clears all strings, BTW
1702 /* Check if we are called with -V or --version parameter */
1703 if (argc
>= 2 && ((strcmp(argv
[1], "-V") == 0) || (strcmp(argv
[1], "--version") == 0))) {
1708 #ifdef CONFIG_AIRPLAY_2
1709 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 10, 0)
1712 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
1713 avcodec_register_all();
1717 /* Check if we are called with -h or --help parameter */
1718 if (argc
>= 2 && ((strcmp(argv
[1], "-h") == 0) || (strcmp(argv
[1], "--help") == 0))) {
1723 /* Check if we are called with -log-to-syslog */
1724 if (argc
>= 2 && (strcmp(argv
[1], "--log-to-syslog") == 0)) {
1725 log_to_syslog_select_is_first_command_line_argument
= 1;
1733 conns
= NULL
; // no connections active
1734 memset((void *)&main_thread_id
, 0, sizeof(main_thread_id
));
1735 ns_time_at_startup
= get_absolute_time_in_ns();
1736 ns_time_at_last_debug_message
= ns_time_at_startup
;
1737 // this is a bit weird, but necessary -- basename() may modify the argument passed in
1738 char *basec
= strdup(argv
[0]);
1739 char *bname
= basename(basec
);
1740 config
.appName
= strdup(bname
);
1741 if (config
.appName
== NULL
)
1742 die("can not allocate memory for the app name!");
1745 #ifdef CONFIG_LIBDAEMON
1746 daemon_set_verbosity(LOG_DEBUG
);
1748 setlogmask(LOG_UPTO(LOG_DEBUG
));
1749 openlog(NULL
, 0, LOG_DAEMON
);
1751 emergency_exit
= 0; // what to do or skip in the exit_function
1752 atexit(exit_function
);
1756 // get a device id -- the first non-local MAC address
1757 get_device_id((uint8_t *)&config
.hw_addr
, 6);
1759 // get the endianness
1765 xn
.arr
[0] = 0x44; /* Lowest-address byte */
1768 xn
.arr
[3] = 0x11; /* Highest-address byte */
1770 if (xn
.u32
== 0x11223344)
1771 config
.endianness
= SS_LITTLE_ENDIAN
;
1772 else if (xn
.u32
== 0x33441122)
1773 config
.endianness
= SS_PDP_ENDIAN
;
1774 else if (xn
.u32
== 0x44332211)
1775 config
.endianness
= SS_BIG_ENDIAN
;
1777 die("Can not recognise the endianness of the processor.");
1779 // set non-zero / non-NULL default values here
1780 // but note that audio back ends also have a chance to set defaults
1782 // get the first output backend in the list and make it the default
1783 audio_output
*first_backend
= audio_get_output(NULL
);
1784 if (first_backend
== NULL
) {
1785 die("No audio backend found! Check your build of Shairport Sync.");
1787 strncpy(first_backend_name
, first_backend
->name
, sizeof(first_backend_name
) - 1);
1788 config
.output_name
= first_backend_name
;
1791 strcpy(configuration_file_path
, SYSCONFDIR
);
1792 // strcat(configuration_file_path, "/shairport-sync"); // thinking about adding a special
1793 // shairport-sync directory
1794 strcat(configuration_file_path
, "/");
1795 strcat(configuration_file_path
, config
.appName
);
1796 strcat(configuration_file_path
, ".conf");
1797 config
.configfile
= configuration_file_path
;
1799 // config.statistics_requested = 0; // don't print stats in the log
1800 // config.userSuppliedLatency = 0; // zero means none supplied
1802 config
.debugger_show_file_and_line
=
1803 1; // by default, log the file and line of the originating message
1804 config
.debugger_show_relative_time
=
1805 1; // by default, log the time back to the previous debug message
1806 config
.resyncthreshold
= 0.05; // 50 ms
1807 config
.timeout
= 120; // this number of seconds to wait for [more] audio before switching to idle.
1809 0.002; // this number of seconds of timing error before attempting to correct it.
1810 config
.buffer_start_fill
= 220;
1812 #ifdef CONFIG_AIRPLAY_2
1813 config
.timeout
= 0; // disable watchdog
1820 config
.packet_stuffing
= ST_auto
; // use soxr interpolation by default if support has been
1821 // included and if the CPU is fast enough
1823 config
.packet_stuffing
= ST_basic
; // simple interpolation or deletion
1826 // char hostname[100];
1827 // gethostname(hostname, 100);
1828 // config.service_name = malloc(20 + 100);
1829 // snprintf(config.service_name, 20 + 100, "Shairport Sync on %s", hostname);
1830 set_requested_connection_state_to_output(
1831 1); // we expect to be able to connect to the output device
1832 config
.audio_backend_buffer_desired_length
= 0.15; // seconds
1833 config
.udp_port_base
= 6001;
1834 config
.udp_port_range
= 10;
1835 config
.output_format
= SPS_FORMAT_S16_LE
; // default
1836 config
.output_format_auto_requested
= 1; // default auto select format
1837 config
.output_rate
= 44100; // default
1838 config
.output_rate_auto_requested
= 1; // default auto select format
1839 config
.decoders_supported
=
1840 1 << decoder_hammerton
; // David Hammerton's decoder supported by default
1841 #ifdef CONFIG_APPLE_ALAC
1842 config
.decoders_supported
+= 1 << decoder_apple_alac
;
1843 config
.use_apple_decoder
= 1; // use the ALAC decoder by default if support has been included
1846 // initialise random number generator
1850 #ifdef CONFIG_LIBDAEMON
1852 /* Reset signal handlers */
1853 if (daemon_reset_sigs(-1) < 0) {
1854 daemon_log(LOG_ERR
, "Failed to reset all signal handlers: %s", strerror(errno
));
1858 /* Unblock signals */
1859 if (daemon_unblock_sigs(-1) < 0) {
1860 daemon_log(LOG_ERR
, "Failed to unblock all signals: %s", strerror(errno
));
1864 /* Set identification string for the daemon for both syslog and PID file */
1865 daemon_pid_file_ident
= daemon_log_ident
= daemon_ident_from_argv0(argv
[0]);
1867 daemon_pid_file_proc
= pid_file_proc
;
1870 // parse arguments into config -- needed to locate pid_dir
1871 int audio_arg
= parse_options(argc
, argv
);
1873 // mDNS supports maximum of 63-character names (we append 13).
1874 if (strlen(config
.service_name
) > 50) {
1875 warn("The service name \"%s\" is too long (max 50 characters) and has been truncated.",
1876 config
.service_name
);
1877 config
.service_name
[50] = '\0'; // truncate it and carry on...
1880 /* Check if we are called with -k or --kill option */
1881 if (killOption
!= 0) {
1882 #ifdef CONFIG_LIBDAEMON
1885 /* Kill daemon with SIGTERM */
1886 /* Check if the new function daemon_pid_file_kill_wait() is available, if it is, use it. */
1887 if ((ret
= daemon_pid_file_kill_wait(SIGTERM
, 5)) < 0) {
1888 if (errno
== ENOENT
)
1889 daemon_log(LOG_WARNING
, "Failed to kill %s daemon: PID file not found.", config
.appName
);
1891 daemon_log(LOG_WARNING
, "Failed to kill %s daemon: \"%s\", errno %u.", config
.appName
,
1892 strerror(errno
), errno
);
1894 // debug(1,"Successfully killed the %s daemon.", config.appName);
1895 if (daemon_pid_file_remove() == 0)
1896 debug(2, "killed the %s daemon.", config
.appName
);
1898 daemon_log(LOG_WARNING
,
1899 "killed the %s daemon, but cannot remove old PID file: \"%s\", errno %u.",
1900 config
.appName
, strerror(errno
), errno
);
1902 return ret
< 0 ? 1 : 0;
1904 fprintf(stderr
, "%s was built without libdaemon, so does not support the -k or --kill option\n",
1910 #ifdef CONFIG_LIBDAEMON
1911 /* If we are going to daemonise, check that the daemon is not running already.*/
1912 if ((config
.daemonise
) && ((pid
= daemon_pid_file_is_running()) >= 0)) {
1913 daemon_log(LOG_ERR
, "The %s daemon is already running as PID %u", config
.appName
, pid
);
1917 /* here, daemonise with libdaemon */
1919 if (config
.daemonise
) {
1920 /* Prepare for return value passing from the initialization procedure of the daemon process */
1921 if (daemon_retval_init() < 0) {
1922 daemon_log(LOG_ERR
, "Failed to create pipe.");
1927 if ((pid
= daemon_fork()) < 0) {
1930 daemon_retval_done();
1933 } else if (pid
) { /* The parent */
1936 /* Wait for 20 seconds for the return value passed from the daemon process */
1937 if ((ret
= daemon_retval_wait(20)) < 0) {
1938 daemon_log(LOG_ERR
, "Could not receive return value from daemon process: %s",
1949 "the %s daemon failed to launch: could not close open file descriptors after forking.",
1953 daemon_log(LOG_ERR
, "the %s daemon failed to launch: could not create PID file.",
1958 "the %s daemon failed to launch: could not create or access PID directory.",
1962 daemon_log(LOG_ERR
, "the %s daemon failed to launch, error %i.", config
.appName
, ret
);
1965 } else { /* pid == 0 means we are the daemon */
1967 this_is_the_daemon_process
= 1; //
1970 if (daemon_close_all(-1) < 0) {
1971 daemon_log(LOG_ERR
, "Failed to close all file descriptors: %s", strerror(errno
));
1972 /* Send the error condition to the parent process */
1973 daemon_retval_send(1);
1975 daemon_signal_done();
1979 /* Create the PID file if required */
1980 if (config
.daemonise_store_pid
) {
1981 /* Create the PID directory if required -- we don't really care about the result */
1982 printf("PID directory is \"%s\".", config
.computed_piddir
);
1983 int result
= mkpath(config
.computed_piddir
, 0700);
1984 if ((result
!= 0) && (result
!= -EEXIST
)) {
1985 // error creating or accessing the PID file directory
1986 daemon_retval_send(3);
1988 daemon_signal_done();
1992 if (daemon_pid_file_create() < 0) {
1993 daemon_log(LOG_ERR
, "Could not create PID file (%s).", strerror(errno
));
1995 daemon_retval_send(2);
1996 daemon_signal_done();
2001 /* Send OK to parent process */
2002 daemon_retval_send(0);
2004 /* end libdaemon stuff */
2009 #ifdef CONFIG_AIRPLAY_2
2011 if (has_fltp_capable_aac_decoder() == 0) {
2012 die("Shairport Sync can not run on this system. Run \"shairport-sync -h\" for more "
2016 uint64_t apf
= config
.airplay_features
;
2017 uint64_t apfh
= config
.airplay_features
;
2019 uint32_t apf32
= apf
;
2020 uint32_t apfh32
= apfh
;
2021 debug(1, "startup in Airplay 2 mode with features 0x%" PRIx32
",0x%" PRIx32
" on device \"%s\".",
2022 apf32
, apfh32
, config
.airplay_device_id
);
2024 debug(1, "startup in Airplay 1 mode.");
2027 // control-c (SIGINT) cleanly
2028 struct sigaction act
;
2029 memset(&act
, 0, sizeof(struct sigaction
));
2030 act
.sa_handler
= intHandler
;
2031 sigaction(SIGINT
, &act
, NULL
);
2033 // terminate (SIGTERM)
2034 struct sigaction act2
;
2035 memset(&act2
, 0, sizeof(struct sigaction
));
2036 act2
.sa_handler
= termHandler
;
2037 sigaction(SIGTERM
, &act2
, NULL
);
2039 // stop a pipe signal from killing the program
2040 signal(SIGPIPE
, SIG_IGN
);
2042 // install a zombie process reaper
2043 // see: http://www.microhowto.info/howto/reap_zombie_processes_using_a_sigchld_handler.html
2044 struct sigaction sa
;
2045 sa
.sa_handler
= &handle_sigchld
;
2046 sigemptyset(&sa
.sa_mask
);
2047 sa
.sa_flags
= SA_RESTART
| SA_NOCLDSTOP
;
2048 if (sigaction(SIGCHLD
, &sa
, 0) == -1) {
2053 main_thread_id
= pthread_self();
2054 if (!main_thread_id
)
2055 debug(1, "Main thread is set up to be NULL!");
2057 // make sure the program can create files that group and world can read
2058 umask(S_IWGRP
| S_IWOTH
);
2060 /* print out version */
2062 char *version_dbs
= get_version_string();
2064 debug(1, "software version: \"%s\"", version_dbs
);
2067 debug(1, "can't print the version information!");
2070 debug(1, "log verbosity is %d.", debuglev
);
2072 config
.output
= audio_get_output(config
.output_name
);
2073 if (!config
.output
) {
2074 die("Invalid audio backend \"%s\" selected!",
2075 config
.output_name
== NULL
? "<unspecified>" : config
.output_name
);
2077 config
.output
->init(argc
- audio_arg
, argv
+ audio_arg
);
2079 // pthread_cleanup_push(main_cleanup_handler, NULL);
2081 // daemon_log(LOG_NOTICE, "startup");
2083 switch (config
.endianness
) {
2084 case SS_LITTLE_ENDIAN
:
2085 debug(2, "The processor is running little-endian.");
2088 debug(2, "The processor is running big-endian.");
2091 debug(2, "The processor is running pdp-endian.");
2095 #ifdef CONFIG_AIRPLAY_2
2096 if (sodium_init() < 0) {
2097 debug(1, "Can't initialise libsodium!");
2099 debug(1, "libsodium initialised.");
2102 // this code is based on
2103 // https://www.gnupg.org/documentation/manuals/gcrypt/Initializing-the-library.html
2105 /* Version check should be the very first call because it
2106 makes sure that important subsystems are initialized.
2107 #define NEED_LIBGCRYPT_VERSION to the minimum required version. */
2109 #define NEED_LIBGCRYPT_VERSION "1.5.4"
2111 if (!gcry_check_version(NEED_LIBGCRYPT_VERSION
)) {
2112 die("libgcrypt is too old (need %s, have %s).", NEED_LIBGCRYPT_VERSION
,
2113 gcry_check_version(NULL
));
2116 /* Disable secure memory. */
2117 gcry_control(GCRYCTL_DISABLE_SECMEM
, 0);
2119 /* ... If required, other initialization goes here. */
2121 /* Tell Libgcrypt that initialization has completed. */
2122 gcry_control(GCRYCTL_INITIALIZATION_FINISHED
, 0);
2126 /* Mess around with the latency options */
2127 // Basically, we expect the source to set the latency and add a fixed offset of 11025 frames to
2128 // it, which sounds right
2129 // If this latency is outside the max and min latensies that may be set by the source, clamp it to
2132 // If they specify a non-standard latency, we suggest the user to use the
2133 // audio_backend_latency_offset instead.
2135 if (config
.userSuppliedLatency
) {
2136 inform("The fixed latency setting is deprecated, as Shairport Sync gets the correct "
2137 "latency automatically from the source.");
2138 inform("Use the audio_backend_latency_offset_in_seconds setting "
2139 "instead to compensate for timing issues.");
2140 if ((config
.userSuppliedLatency
!= 0) &&
2141 ((config
.userSuppliedLatency
< 4410) ||
2142 (config
.userSuppliedLatency
> BUFFER_FRAMES
* 352 - 22050)))
2143 die("An out-of-range fixed latency has been specified. It must be between 4410 and %d (at "
2144 "44100 frames per second).",
2145 BUFFER_FRAMES
* 352 - 22050);
2148 /* Print out options */
2149 debug(1, "disable resend requests is %s.", config
.disable_resend_requests
? "on" : "off");
2151 "diagnostic_drop_packet_fraction is %f. A value of 0.0 means no packets will be dropped "
2153 config
.diagnostic_drop_packet_fraction
);
2154 debug(1, "statistics_requester status is %d.", config
.statistics_requested
);
2155 #if CONFIG_LIBDAEMON
2156 debug(1, "daemon status is %d.", config
.daemonise
);
2157 debug(1, "daemon pid file path is \"%s\".", pid_file_proc());
2159 debug(1, "rtsp listening port is %d.", config
.port
);
2160 debug(1, "udp base port is %d.", config
.udp_port_base
);
2161 debug(1, "udp port range is %d.", config
.udp_port_range
);
2162 debug(1, "player name is \"%s\".", config
.service_name
);
2163 debug(1, "backend is \"%s\".", config
.output_name
);
2164 debug(1, "run_this_before_play_begins action is \"%s\".", strnull(config
.cmd_start
));
2165 debug(1, "run_this_after_play_ends action is \"%s\".", strnull(config
.cmd_stop
));
2166 debug(1, "wait-cmd status is %d.", config
.cmd_blocking
);
2167 debug(1, "run_this_before_play_begins may return output is %d.", config
.cmd_start_returns_output
);
2168 debug(1, "run_this_if_an_unfixable_error_is_detected action is \"%s\".",
2169 strnull(config
.cmd_unfixable
));
2170 debug(1, "run_this_before_entering_active_state action is \"%s\".",
2171 strnull(config
.cmd_active_start
));
2172 debug(1, "run_this_after_exiting_active_state action is \"%s\".",
2173 strnull(config
.cmd_active_stop
));
2174 debug(1, "active_state_timeout is %f seconds.", config
.active_state_timeout
);
2175 debug(1, "mdns backend \"%s\".", strnull(config
.mdns_name
));
2176 debug(2, "userSuppliedLatency is %d.", config
.userSuppliedLatency
);
2177 debug(1, "interpolation setting is \"%s\".",
2178 config
.packet_stuffing
== ST_basic
? "basic"
2179 : config
.packet_stuffing
== ST_soxr
? "soxr" : "auto");
2180 debug(1, "interpolation soxr_delay_threshold is %d.", config
.soxr_delay_threshold
);
2181 debug(1, "resync time is %f seconds.", config
.resyncthreshold
);
2182 debug(1, "allow a session to be interrupted: %d.", config
.allow_session_interruption
);
2183 debug(1, "busy timeout time is %d.", config
.timeout
);
2184 debug(1, "drift tolerance is %f seconds.", config
.tolerance
);
2185 debug(1, "password is \"%s\".", strnull(config
.password
));
2186 debug(1, "ignore_volume_control is %d.", config
.ignore_volume_control
);
2187 if (config
.volume_max_db_set
)
2188 debug(1, "volume_max_db is %d.", config
.volume_max_db
);
2190 debug(1, "volume_max_db is not set");
2191 debug(1, "volume range in dB (zero means use the range specified by the mixer): %u.",
2192 config
.volume_range_db
);
2194 "volume_range_combined_hardware_priority (1 means hardware mixer attenuation is used "
2196 config
.volume_range_hw_priority
);
2197 debug(1, "playback_mode is %d (0-stereo, 1-mono, 1-reverse_stereo, 2-both_left, 3-both_right).",
2198 config
.playback_mode
);
2199 debug(1, "disable_synchronization is %d.", config
.no_sync
);
2200 debug(1, "use_mmap_if_available is %d.", config
.no_mmap
? 0 : 1);
2201 debug(1, "output_format automatic selection is %sabled.",
2202 config
.output_format_auto_requested
? "en" : "dis");
2203 if (config
.output_format_auto_requested
== 0)
2204 debug(1, "output_format is \"%s\".", sps_format_description_string(config
.output_format
));
2205 debug(1, "output_rate automatic selection is %sabled.",
2206 config
.output_rate_auto_requested
? "en" : "dis");
2207 if (config
.output_rate_auto_requested
== 0)
2208 debug(1, "output_rate is %d.", config
.output_rate
);
2209 debug(1, "audio backend desired buffer length is %f seconds.",
2210 config
.audio_backend_buffer_desired_length
);
2211 debug(1, "audio_backend_buffer_interpolation_threshold_in_seconds is %f seconds.",
2212 config
.audio_backend_buffer_interpolation_threshold_in_seconds
);
2213 debug(1, "audio backend latency offset is %f seconds.", config
.audio_backend_latency_offset
);
2214 if (config
.audio_backend_silent_lead_in_time_auto
== 1)
2215 debug(1, "audio backend silence lead-in time is \"auto\".");
2217 debug(1, "audio backend silence lead-in time is %f seconds.",
2218 config
.audio_backend_silent_lead_in_time
);
2219 debug(1, "zeroconf regtype is \"%s\".", config
.regtype
);
2220 debug(1, "decoders_supported field is %d.", config
.decoders_supported
);
2221 debug(1, "use_apple_decoder is %d.", config
.use_apple_decoder
);
2222 debug(1, "alsa_use_hardware_mute is %d.", config
.alsa_use_hardware_mute
);
2223 if (config
.interface
)
2224 debug(1, "mdns service interface \"%s\" requested.", config
.interface
);
2226 debug(1, "no special mdns service interface was requested.");
2227 char *realConfigPath
= realpath(config
.configfile
, NULL
);
2228 if (realConfigPath
) {
2229 debug(1, "configuration file name \"%s\" resolves to \"%s\".", config
.configfile
,
2231 free(realConfigPath
);
2233 debug(1, "configuration file name \"%s\" can not be resolved.", config
.configfile
);
2235 #ifdef CONFIG_METADATA
2236 debug(1, "metadata enabled is %d.", config
.metadata_enabled
);
2237 debug(1, "metadata pipename is \"%s\".", config
.metadata_pipename
);
2238 debug(1, "metadata socket address is \"%s\" port %d.", config
.metadata_sockaddr
,
2239 config
.metadata_sockport
);
2240 debug(1, "metadata socket packet size is \"%d\".", config
.metadata_sockmsglength
);
2241 debug(1, "get-coverart is %d.", config
.get_coverart
);
2244 debug(1, "mqtt is %sabled.", config
.mqtt_enabled
? "en" : "dis");
2245 debug(1, "mqtt hostname is %s, port is %d.", config
.mqtt_hostname
, config
.mqtt_port
);
2246 debug(1, "mqtt topic is %s.", config
.mqtt_topic
);
2247 debug(1, "mqtt will%s publish raw metadata.", config
.mqtt_publish_raw
? "" : " not");
2248 debug(1, "mqtt will%s publish parsed metadata.", config
.mqtt_publish_parsed
? "" : " not");
2249 debug(1, "mqtt will%s publish cover Art.", config
.mqtt_publish_cover
? "" : " not");
2250 debug(1, "mqtt remote control is %sabled.", config
.mqtt_enable_remote
? "en" : "dis");
2253 #ifdef CONFIG_CONVOLUTION
2254 debug(1, "convolution is %d.", config
.convolution
);
2255 debug(1, "convolution IR file is \"%s\"", config
.convolution_ir_file
);
2256 debug(1, "convolution max length %d", config
.convolution_max_length
);
2257 debug(1, "convolution gain is %f", config
.convolution_gain
);
2259 debug(1, "loudness is %d.", config
.loudness
);
2260 debug(1, "loudness reference level is %f", config
.loudness_reference_volume_db
);
2263 pthread_create(&soxr_time_check_thread
, NULL
, &soxr_time_check
, NULL
);
2269 #ifdef CONFIG_OPENSSL
2272 MD5_Update(&ctx, config.service_name, strlen(config.service_name));
2273 MD5_Final(ap_md5, &ctx);
2276 #ifdef CONFIG_MBEDTLS
2277 #if MBEDTLS_VERSION_MINOR >= 7
2278 mbedtls_md5_context tctx;
2279 mbedtls_md5_starts_ret(&tctx);
2280 mbedtls_md5_update_ret(&tctx, (unsigned char *)config.service_name,
2281 strlen(config.service_name)); mbedtls_md5_finish_ret(&tctx, ap_md5); #else mbedtls_md5_context
2282 tctx; mbedtls_md5_starts(&tctx); mbedtls_md5_update(&tctx, (unsigned char *)config.service_name,
2283 strlen(config.service_name)); mbedtls_md5_finish(&tctx, ap_md5); #endif #endif
2285 #ifdef CONFIG_POLARSSL
2288 md5_update(&tctx, (unsigned char *)config.service_name, strlen(config.service_name));
2289 md5_finish(&tctx, ap_md5);
2292 memcpy(config.hw_addr, ap_md5, sizeof(config.hw_addr));
2295 #ifdef CONFIG_METADATA
2296 metadata_init(); // create the metadata pipe if necessary
2299 #ifdef CONFIG_METADATA_HUB
2300 // debug(1, "Initialising metadata hub");
2301 metadata_hub_init();
2304 #ifdef CONFIG_DACP_CLIENT
2305 // debug(1, "Requesting DACP Monitor");
2306 dacp_monitor_start();
2309 #if defined(CONFIG_DBUS_INTERFACE) || defined(CONFIG_MPRIS_INTERFACE)
2310 // Start up DBUS services after initial settings are all made
2311 // debug(1, "Starting up D-Bus services");
2312 pthread_create(&dbus_thread
, NULL
, &dbus_thread_func
, NULL
);
2313 #ifdef CONFIG_DBUS_INTERFACE
2314 start_dbus_service();
2316 #ifdef CONFIG_MPRIS_INTERFACE
2317 start_mpris_service();
2322 if (config
.mqtt_enabled
) {
2327 #ifdef CONFIG_AIRPLAY_2
2328 ptp_send_control_message_string("T"); // get nqptp to create the named shm interface
2329 int ptp_check_times
= 0;
2330 const int ptp_wait_interval_us
= 5000;
2331 // wait for up to ten seconds for NQPTP to come online
2333 ptp_send_control_message_string("T"); // get nqptp to create the named shm interface
2334 usleep(ptp_wait_interval_us
);
2336 } while ((ptp_shm_interface_open() != 0) && (ptp_check_times
< (10000000 / ptp_wait_interval_us
)));
2338 if (ptp_shm_interface_open() != 0) {
2339 die("Can't access NQPTP! Is it installed and running?");
2341 if (ptp_check_times
== 1)
2342 debug(1, "NQPTP is online.");
2344 debug(1, "NQPTP is online after %u microseconds.", ptp_check_times
* ptp_wait_interval_us
);
2348 activity_monitor_start(); // not yet for AP2
2349 pthread_create(&rtsp_listener_thread
, NULL
, &rtsp_listen_loop
, NULL
);
2350 atexit(exit_rtsp_listener
);
2351 pthread_join(rtsp_listener_thread
, NULL
);