12 #include <sys/socket.h>
18 #include "definitions.h"
21 // struct sockaddr_in6 is bigger than struct sockaddr. derp
23 #define SOCKADDR struct sockaddr_storage
24 #define SAFAMILY ss_family
26 #define SOCKADDR struct sockaddr
27 #define SAFAMILY sa_family
30 #if defined(CONFIG_DBUS_INTERFACE) || defined(CONFIG_MPRIS_INTERFACE)
32 DBT_system
= 0, // use the session bus
33 DBT_session
, // use the system bus
40 TOE_dbus
// a request was made on a D-Bus interface (the native D-Bus or MPRIS interfaces)-- don't
41 // wait for the dbus thread to exit
44 #define sps_extra_code_output_stalled 32768
45 #define sps_extra_code_output_state_cannot_make_ready 32769
48 typedef enum { YNA_AUTO
= -1, YNA_NO
= 0, YNA_YES
= 1 } yna_type
;
51 typedef enum { YNDK_DONT_KNOW
= -1, YNDK_NO
= 0, YNDK_YES
= 1 } yndk_type
;
60 ST_basic
= 0, // straight deletion or insertion of a frame in a 352-frame packet
61 ST_soxr
, // use libsoxr to make a 352 frame packet one frame longer or shorter
62 ST_auto
, // use soxr if compiled for it and if the soxr_index is low enough
77 } volume_control_profile_type
;
80 decoder_hammerton
= 0,
82 } decoders_supported_type
;
85 disable_standby_off
= 0,
87 disable_standby_always
88 } disable_standby_mode_type
;
90 // the following enum is for the formats recognised -- currently only S16LE is recognised for input,
91 // so these are output only for the present
94 SPS_FORMAT_UNKNOWN
= 0,
112 const char *sps_format_description_string(sps_format_t format
);
115 double missing_port_dacp_scan_interval_seconds
; // if no DACP port number can be found, check at
117 double resend_control_first_check_time
; // wait this long before asking for a missing packet to be
119 double resend_control_check_interval_time
; // wait this long between making requests
120 double resend_control_last_check_time
; // if the packet is missing this close to the time of use,
122 pthread_mutex_t lock
;
125 double airplay_volume
; // stored here for reloading when necessary
126 double default_airplay_volume
;
127 double high_threshold_airplay_volume
;
128 uint64_t last_access_to_volume_info_time
;
129 int limit_to_high_volume_threshold_time_in_minutes
; // revert to the high threshold volume level
130 // if the existing volume level exceeds this
131 // and hasn't been used for this amount of
132 // time (0 means never revert)
133 char *appName
; // normally the app is called shairport-syn, but it may be symlinked
135 char *service_name
; // the name for the shairport service, e.g. "Shairport Sync Version %v running
139 char *pa_server
; // the pulseaudio server address that Shairport Sync will play on.
140 char *pa_application_name
; // the name under which Shairport Sync shows up as an "Application" in
141 // the Sound Preferences in most desktop Linuxes.
142 // Defaults to "Shairport Sync". Shairport Sync must be playing to see it.
144 char *pa_sink
; // the name (or id) of the sink that Shairport Sync will play on.
146 #ifdef CONFIG_METADATA
147 int metadata_enabled
;
148 char *metadata_pipename
;
149 char *metadata_sockaddr
;
150 int metadata_sockport
;
151 size_t metadata_sockmsglength
;
153 double metadata_progress_interval
; // 0 means no progress reports
166 int mqtt_publish_raw
;
167 int mqtt_publish_parsed
;
168 int mqtt_publish_cover
;
169 int mqtt_enable_remote
;
170 char *mqtt_empty_payload_substitute
;
172 uint8_t ap1_prefix
[6];
173 uint8_t hw_addr
[8]; // only needs 6 but 8 is handy when converting this to a number
177 int ignore_volume_control
;
178 int volume_max_db_set
; // set to 1 if a maximum volume db has been set
180 int no_sync
; // disable synchronisation, even if it's available
181 int no_mmap
; // disable use of mmap-based output, even if it's available
182 double resync_threshold
; // if it gets out of whack by more than this number of seconds, do a
183 // resync. if zero, never do a resync.
184 double resync_recovery_time
; // if sync is late, drop the delay but also drop the following frames
185 // up to the resync_recovery_time
186 int allow_session_interruption
;
187 int timeout
; // while in play mode, exit if no packets of audio come in for more than this number
188 // of seconds . Zero means never exit.
189 int dont_check_timeout
; // this is used to maintain backward compatibility with the old -t option
190 // behaviour; only set by -t 0, cleared by everything else
192 audio_output
*output
;
195 int buffer_start_fill
;
196 uint32_t userSuppliedLatency
; // overrides all other latencies -- use with caution
197 uint32_t fixedLatencyOffset
; // add this to all automatic latencies supplied to get the actual
199 // the total latency will be limited to the min and max-latency values, if supplied
200 #ifdef CONFIG_LIBDAEMON
202 int daemonise_store_pid
; // don't try to save a PID file
204 char *computed_piddir
; // the actual pid directory to create, if any
208 int log_fd
; // file descriptor of the file or pipe to log stuff to.
209 char *log_file_path
; // path to file or pipe to log to, if any
210 int logOutputLevel
; // log output level
211 int debugger_show_elapsed_time
; // in the debug message, display the time since startup
212 int debugger_show_relative_time
; // in the debug message, display the time since the last one
213 int debugger_show_file_and_line
; // in the debug message, display the filename and line number
214 int statistics_requested
, use_negotiated_latencies
;
215 playback_mode_type playback_mode
;
216 char *cmd_start
, *cmd_stop
, *cmd_set_volume
, *cmd_unfixable
;
217 char *cmd_active_start
, *cmd_active_stop
;
218 int cmd_blocking
, cmd_start_returns_output
;
219 double tolerance
; // allow this much drift before attempting to correct it
220 stuffing_type packet_stuffing
;
221 int soxr_delay_index
;
222 int soxr_delay_threshold
; // the soxr delay must be less or equal to this for soxr interpolation
223 // to be enabled under the auto setting
224 int decoders_supported
;
225 int use_apple_decoder
; // set to 1 if you want to use the apple decoder instead of the original by
230 char *regtype
; // The regtype is the service type followed by the protocol, separated by a dot, by
231 // default “_raop._tcp.” for AirPlay 1.
232 char *regtype2
; // The regtype is the service type followed by the protocol, separated by a dot,
233 // by default “_raop._tcp.” for AirPlay 2.
234 char *interface
; // a string containg the interface name, or NULL if nothing specified
235 int interface_index
; // only valid if the interface string is non-NULL
236 double audio_backend_buffer_desired_length
; // this will be the length in seconds of the
237 // audio backend buffer -- the DAC buffer for ALSA
238 double audio_backend_buffer_interpolation_threshold_in_seconds
; // below this, soxr interpolation
239 // will not occur -- it'll be
240 // basic interpolation instead.
241 double disable_standby_mode_silence_threshold
; // below this, silence will be added to the output
243 double disable_standby_mode_silence_scan_interval
; // check the threshold this often
245 double audio_backend_latency_offset
; // this will be the offset in seconds to compensate for any
246 // fixed latency there might be in the audio path
247 int audio_backend_silent_lead_in_time_auto
; // true if the lead-in time should be from as soon as
248 // packets are received
249 double audio_backend_silent_lead_in_time
; // the length of the silence that should precede a play.
250 uint32_t minimum_free_buffer_headroom
; // when effective latency is calculated, ensure this number
251 // of buffers are unallocated
252 double active_state_timeout
; // the amount of time from when play ends to when the system leaves
253 // into the "active" mode.
254 uint32_t volume_range_db
; // the range, in dB, from max dB to min dB. Zero means use the mixer's
256 int volume_range_hw_priority
; // when extending the volume range by combining sw and hw
257 // attenuators, lowering the volume, use all the hw attenuation
260 volume_control_profile_type volume_control_profile
;
262 int output_format_auto_requested
; // true if the configuration requests auto configuration
263 sps_format_t output_format
;
264 int output_rate_auto_requested
; // true if the configuration requests auto configuration
265 unsigned int output_rate
;
267 #ifdef CONFIG_CONVOLUTION
270 char *convolution_ir_file
;
271 float convolution_gain
;
272 int convolution_max_length
;
276 float loudness_reference_volume_db
;
277 int alsa_use_hardware_mute
;
278 double alsa_maximum_stall_time
;
279 disable_standby_mode_type disable_standby_mode
;
280 volatile int keep_dac_busy
;
281 yna_type use_precision_timing
; // defaults to no
283 #if defined(CONFIG_DBUS_INTERFACE)
284 dbus_session_type dbus_service_bus_type
;
286 #if defined(CONFIG_MPRIS_INTERFACE)
287 dbus_session_type mpris_service_bus_type
;
290 #ifdef CONFIG_METADATA_HUB
291 char *cover_art_cache_dir
;
294 int scan_interval_when_active
; // number of seconds between DACP server scans when playing
296 int scan_interval_when_inactive
; // number of seconds between DACP server scans playing nothing
298 int scan_max_bad_response_count
; // number of successive bad results to ignore before giving up
300 int scan_max_inactive_count
; // number of scans to do before stopping if not made active again
301 // (about 15 minutes worth)
303 int disable_resend_requests
; // set this to stop resend request being made for missing packets
304 double diagnostic_drop_packet_fraction
; // pseudo randomly drop this fraction of packets, for
305 // debugging. Currently audio packets only...
307 char *jack_client_name
;
308 char *jack_autoconnect_pattern
;
310 int jack_soxr_resample_quality
;
313 void *gradients
; // a linked list of the clock gradients discovered for all DACP IDs
314 // can't use IP numbers as they might be given to different devices
315 // can't get hold of MAC addresses.
316 // can't define the nvll linked list struct here
318 #ifdef CONFIG_AIRPLAY_2
319 uint64_t airplay_features
;
320 uint32_t airplay_statusflags
;
321 char *airplay_device_id
; // for the Bonjour advertisement and the GETINFO PList
322 char *airplay_pin
; // non-NULL, 4 char PIN, if required for pairing
323 char *airplay_pi
; // UUID in the Bonjour advertisement and the GETINFO Plist
324 char *nqptp_shared_memory_interface_name
; // client name for nqptp service
326 int unfixable_error_reported
; // only report once.
329 uint32_t nctohl(const uint8_t *p
); // read 4 characters from *p and do ntohl on them
330 uint16_t nctohs(const uint8_t *p
); // read 2 characters from *p and do ntohs on them
331 uint64_t nctoh64(const uint8_t *p
); // read 8 characters from *p to a uint64_t
333 void memory_barrier();
335 void log_to_stderr(); // call this to direct logging to stderr;
336 void log_to_stdout(); // call this to direct logging to stdout;
337 void log_to_syslog(); // call this to direct logging to the system log;
338 void log_to_file(); // call this to direct logging to a file or (pre-existing) pipe;
340 // true if Shairport Sync is supposed to be sending output to the output device, false otherwise
342 int get_requested_connection_state_to_output();
344 void set_requested_connection_state_to_output(int v
);
346 int try_to_open_pipe_for_writing(
347 const char *pathname
); // open it without blocking if it's not hooked up
350 * http://coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring#comment-722
352 char *str_replace(const char *string
, const char *substr
, const char *replacement
);
354 // based on http://burtleburtle.net/bob/rand/smallprng.html
356 void r64init(uint64_t seed
);
360 // if you are breaking in to a session, you need to avoid the ports of the current session
361 // if you are law-abiding, then you can reuse the ports.
362 // so, you can reset the free UDP ports minder when you're legit, and leave it otherwise
364 // the downside of using different ports each time is that it might make the firewall
365 // rules a bit more complex, as they need to allow more than the minimum three ports.
366 // a range of 10 is suggested anyway
368 void resetFreeUDPPort();
369 uint16_t nextFreeUDPPort();
371 extern volatile int debuglev
;
373 void _die(const char *filename
, const int linenumber
, const char *format
, ...);
374 void _warn(const char *filename
, const int linenumber
, const char *format
, ...);
375 void _inform(const char *filename
, const int linenumber
, const char *format
, ...);
376 void _debug(const char *filename
, const int linenumber
, int level
, const char *format
, ...);
378 #define die(...) _die(__FILE__, __LINE__, __VA_ARGS__)
379 #define debug(...) _debug(__FILE__, __LINE__, __VA_ARGS__)
380 #define warn(...) _warn(__FILE__, __LINE__, __VA_ARGS__)
381 #define inform(...) _inform(__FILE__, __LINE__, __VA_ARGS__)
383 uint8_t *base64_dec(char *input
, int *outlen
);
384 char *base64_enc(uint8_t *input
, int length
);
386 #define RSA_MODE_AUTH (0)
387 #define RSA_MODE_KEY (1)
388 uint8_t *rsa_apply(uint8_t *input
, int inlen
, int *outlen
, int mode
);
390 // given a volume (0 to -30) and high and low attenuations in dB*100 (e.g. 0 to -6000 for 0 to -60
391 // dB), return an attenuation depending on a linear interpolation along the range
392 double flat_vol2attn(double vol
, long max_db
, long min_db
);
394 // The intention behind dasl_tapered is that a given percentage change in volume should result in
395 // the same percentage change in perceived loudness. For instance, doubling the volume level should
396 // result in doubling the perceived loudness. With the range of AirPlay volume being from -30 to 0,
397 // doubling the volume from -22.5 to -15 results in an increase of 10 dB. Similarly, doubling the
398 // volume from -15 to 0 results in an increase of 10 dB. For compatibility with mixers having a
399 // restricted attenuation range (e.g. 30 dB), "dasl_tapered" will switch to a flat profile at low
401 double dasl_tapered_vol2attn(double vol
, long max_db
, long min_db
);
402 // given a volume (0 to -30) and high and low attenuations in dB*100 (e.g. 0 to -6000 for 0 to -60
403 // dB), return an attenuation depending on the transfer function
404 double vol2attn(double vol
, long max_db
, long min_db
);
406 // return a time in nanoseconds
407 #ifdef COMPILE_FOR_LINUX_AND_FREEBSD_AND_CYGWIN_AND_OPENBSD
408 // Not defined for macOS
409 uint64_t get_realtime_in_ns(void);
411 uint64_t get_absolute_time_in_ns(void); // monotonic_raw or monotonic
412 uint64_t get_monotonic_time_in_ns(void); // NTP-disciplined
414 // time at startup for debugging timing
415 extern uint64_t ns_time_at_startup
, ns_time_at_last_debug_message
;
417 // this is for reading an unsigned 32 bit number, such as an RTP timestamp
419 uint32_t uatoi(const char *nptr
);
421 extern shairport_cfg config
;
422 extern config_t config_file_stuff
;
423 extern int type_of_exit_cleanup
; // normal, emergency, dbus requested...
425 int config_set_lookup_bool(config_t
*cfg
, char *where
, int *dst
);
427 void command_start(void);
428 void command_stop(void);
429 void command_execute(const char *command
, const char *extra_argument
, const int block
);
430 void command_set_volume(double volume
);
432 int mkpath(const char *path
, mode_t mode
);
434 void shairport_shutdown();
436 extern sigset_t pselect_sigset
;
438 extern pthread_mutex_t the_conn_lock
;
440 #define conn_lock(arg) \
441 pthread_mutex_lock(&the_conn_lock); \
443 pthread_mutex_unlock(&the_conn_lock);
445 // wait for the specified time in microseconds -- it checks every 20 milliseconds
446 // int sps_pthread_mutex_timedlock(pthread_mutex_t *mutex, useconds_t dally_time,
447 // const char *debugmessage, int debuglevel);
448 // wait for the specified time, checking every 20 milliseconds, and block if it can't acquire the
450 int _debug_mutex_lock(pthread_mutex_t
*mutex
, useconds_t dally_time
, const char *mutexName
,
451 const char *filename
, const int line
, int debuglevel
);
453 #define debug_mutex_lock(mu, t, d) _debug_mutex_lock(mu, t, #mu, __FILE__, __LINE__, d)
455 int _debug_mutex_unlock(pthread_mutex_t
*mutex
, const char *mutexName
, const char *filename
,
456 const int line
, int debuglevel
);
458 #define debug_mutex_unlock(mu, d) _debug_mutex_unlock(mu, #mu, __FILE__, __LINE__, d)
460 void pthread_cleanup_debug_mutex_unlock(void *arg
);
462 #define pthread_cleanup_debug_mutex_lock(mu, t, d) \
463 if (_debug_mutex_lock(mu, t, #mu, __FILE__, __LINE__, d) == 0) \
464 pthread_cleanup_push(pthread_cleanup_debug_mutex_unlock, (void *)mu)
466 #define config_lock \
467 if (pthread_mutex_trylock(&config.lock) != 0) { \
468 debug(1, "config_lock: cannot acquire config.lock"); \
471 #define config_unlock pthread_mutex_unlock(&config.lock)
473 extern pthread_mutex_t r64_mutex
;
475 #define r64_lock pthread_mutex_lock(&r64_mutex)
477 #define r64_unlock pthread_mutex_unlock(&r64_mutex)
479 char *get_version_string(); // mallocs a string space -- remember to free it afterwards
481 int64_t generate_zero_frames(char *outp
, size_t number_of_frames
, sps_format_t format
,
482 int with_dither
, int64_t random_number_in
);
484 void malloc_cleanup(void *arg
);
486 int string_update_with_size(char **str
, int *flag
, char *s
, size_t len
);
488 // from https://stackoverflow.com/questions/13663617/memdup-function-in-c, with thanks
489 void *memdup(const void *mem
, size_t size
);
491 int bind_socket_and_port(int type
, int ip_family
, const char *self_ip_address
, uint32_t scope_id
,
492 uint16_t *port
, int *sock
);
494 uint16_t bind_UDP_port(int ip_family
, const char *self_ip_address
, uint32_t scope_id
, int *sock
);
496 void socket_cleanup(void *arg
);
497 void mutex_unlock(void *arg
);
498 void mutex_cleanup(void *arg
);
499 void cv_cleanup(void *arg
);
500 void thread_cleanup(void *arg
);
501 #ifdef CONFIG_AIRPLAY_2
502 void plist_cleanup(void *arg
);
505 char *debug_malloc_hex_cstring(void *packet
, size_t nread
);
507 // from https://stackoverflow.com/questions/13663617/memdup-function-in-c, with thanks
508 // allocates memory and copies the content to it
509 // analogous to strndup;
510 void *memdup(const void *mem
, size_t size
);
512 // the difference between two unsigned 32-bit modulo values as a signed 32-bit result
513 // now, if the two numbers are constrained to be within 2^(n-1)-1 of one another,
514 // we can use their as a signed 2^n bit number which will be positive
515 // if the first number is the same or "after" the second, and
516 // negative otherwise
518 int32_t mod32Difference(uint32_t a
, uint32_t b
);
520 int get_device_id(uint8_t *id
, int int_length
);
522 #ifdef CONFIG_USE_GIT_VERSION_STRING
523 extern char git_version_string
[];