1 #ifndef _COMMON_H
2 #define _COMMON_H
3 
4 #include <libconfig.h>
5 #include <pthread.h>
6 #include <signal.h>
7 #include <stdint.h>
8 #include <sys/socket.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 
12 #include "audio.h"
13 #include "config.h"
14 #include "definitions.h"
15 #include "mdns.h"
16 
17 // struct sockaddr_in6 is bigger than struct sockaddr. derp
18 #ifdef AF_INET6
19 #define SOCKADDR struct sockaddr_storage
20 #define SAFAMILY ss_family
21 #else
22 #define SOCKADDR struct sockaddr
23 #define SAFAMILY sa_family
24 #endif
25 
26 #if defined(CONFIG_DBUS_INTERFACE) || defined(CONFIG_MPRIS_INTERFACE)
27 typedef enum {
28   DBT_system = 0, // use the session bus
29   DBT_session,    // use the system bus
30 } dbus_session_type;
31 #endif
32 
33 #define sps_extra_code_output_stalled 32768
34 #define sps_extra_code_output_state_cannot_make_ready 32769
35 
36 // yeah/no/auto
37 typedef enum { YNA_AUTO = -1, YNA_NO = 0, YNA_YES = 1 } yna_type;
38 
39 // yeah/no/dont-care
40 typedef enum { YNDK_DONT_KNOW = -1, YNDK_NO = 0, YNDK_YES = 1 } yndk_type;
41 
42 typedef enum {
43   SS_LITTLE_ENDIAN = 0,
44   SS_PDP_ENDIAN,
45   SS_BIG_ENDIAN,
46 } endian_type;
47 
48 typedef enum {
49   ST_basic = 0, // straight deletion or insertion of a frame in a 352-frame packet
50   ST_soxr,      // use libsoxr to make a 352 frame packet one frame longer or shorter
51   ST_auto,      // use soxr if compiled for it and if the soxr_index is low enough
52 } stuffing_type;
53 
54 typedef enum {
55   ST_stereo = 0,
56   ST_mono,
57   ST_reverse_stereo,
58   ST_left_only,
59   ST_right_only,
60 } playback_mode_type;
61 
62 typedef enum {
63   VCP_standard = 0,
64   VCP_flat,
65 } volume_control_profile_type;
66 
67 typedef enum {
68   decoder_hammerton = 0,
69   decoder_apple_alac,
70 } decoders_supported_type;
71 
72 typedef enum {
73   disable_standby_off = 0,
74   disable_standby_auto,
75   disable_standby_always
76 } disable_standby_mode_type;
77 
78 // the following enum is for the formats recognised -- currently only S16LE is recognised for input,
79 // so these are output only for the present
80 
81 typedef enum {
82   SPS_FORMAT_UNKNOWN = 0,
83   SPS_FORMAT_S8,
84   SPS_FORMAT_U8,
85   SPS_FORMAT_S16,
86   SPS_FORMAT_S16_LE,
87   SPS_FORMAT_S16_BE,
88   SPS_FORMAT_S24,
89   SPS_FORMAT_S24_LE,
90   SPS_FORMAT_S24_BE,
91   SPS_FORMAT_S24_3LE,
92   SPS_FORMAT_S24_3BE,
93   SPS_FORMAT_S32,
94   SPS_FORMAT_S32_LE,
95   SPS_FORMAT_S32_BE,
96   SPS_FORMAT_AUTO,
97   SPS_FORMAT_INVALID,
98 } sps_format_t;
99 
100 const char *sps_format_description_string(sps_format_t format);
101 
102 typedef struct {
103   double missing_port_dacp_scan_interval_seconds; // if no DACP port number can be found, check at
104                                                   // these intervals
105   double resend_control_first_check_time; // wait this long before asking for a missing packet to be
106                                           // resent
107   double resend_control_check_interval_time; // wait this long between making requests
108   double resend_control_last_check_time; // if the packet is missing this close to the time of use,
109                                          // give up
110   pthread_mutex_t lock;
111   config_t *cfg;
112   int endianness;
113   double airplay_volume; // stored here for reloading when necessary
114   char *appName;         // normally the app is called shairport-syn, but it may be symlinked
115   char *password;
116   char *service_name; // the name for the shairport service, e.g. "Shairport Sync Version %v running
117                       // on host %h"
118 
119 #ifdef CONFIG_PA
120   char *pa_server;           // the pulseaudio server address that Shairport Sync will play on.
121   char *pa_application_name; // the name under which Shairport Sync shows up as an "Application" in
122                              // the Sound Preferences in most desktop Linuxes.
123   // Defaults to "Shairport Sync". Shairport Sync must be playing to see it.
124 
125   char *pa_sink; // the name (or id) of the sink that Shairport Sync will play on.
126 #endif
127 #ifdef CONFIG_METADATA
128   int metadata_enabled;
129   char *metadata_pipename;
130   char *metadata_sockaddr;
131   int metadata_sockport;
132   size_t metadata_sockmsglength;
133   int get_coverart;
134 #endif
135 #ifdef CONFIG_MQTT
136   int mqtt_enabled;
137   char *mqtt_hostname;
138   int mqtt_port;
139   char *mqtt_username;
140   char *mqtt_password;
141   char *mqtt_capath;
142   char *mqtt_cafile;
143   char *mqtt_certfile;
144   char *mqtt_keyfile;
145   char *mqtt_topic;
146   int mqtt_publish_raw;
147   int mqtt_publish_parsed;
148   int mqtt_publish_cover;
149   int mqtt_enable_remote;
150 #endif
151   uint8_t hw_addr[6];
152   int port;
153   int udp_port_base;
154   int udp_port_range;
155   int ignore_volume_control;
156   int volume_max_db_set; // set to 1 if a maximum volume db has been set
157   int volume_max_db;
158   int no_sync;            // disable synchronisation, even if it's available
159   int no_mmap;            // disable use of mmap-based output, even if it's available
160   double resyncthreshold; // if it get's out of whack my more than this number of seconds, resync.
161                           // Zero means never
162                           // resync.
163   int allow_session_interruption;
164   int timeout; // while in play mode, exit if no packets of audio come in for more than this number
165                // of seconds . Zero means never exit.
166   int dont_check_timeout; // this is used to maintain backward compatibility with the old -t option
167                           // behaviour; only set by -t 0, cleared by everything else
168   char *output_name;
169   audio_output *output;
170   char *mdns_name;
171   mdns_backend *mdns;
172   int buffer_start_fill;
173   uint32_t userSuppliedLatency; // overrides all other latencies -- use with caution
174   uint32_t fixedLatencyOffset;  // add this to all automatic latencies supplied to get the actual
175                                 // total latency
176 // the total latency will be limited to the min and max-latency values, if supplied
177 #ifdef CONFIG_LIBDAEMON
178   int daemonise;
179   int daemonise_store_pid; // don't try to save a PID file
180   char *piddir;
181   char *computed_piddir; // the actual pid directory to create, if any
182   char *pidfile;
183 #endif
184 
185   int log_fd;                      // file descriptor of the file or pipe to log stuff to.
186   char *log_file_path;             // path to file or pipe to log to, if any
187   int logOutputLevel;              // log output level
188   int debugger_show_elapsed_time;  // in the debug message, display the time since startup
189   int debugger_show_relative_time; // in the debug message, display the time since the last one
190   int debugger_show_file_and_line; // in the debug message, display the filename and line number
191   int statistics_requested, use_negotiated_latencies;
192   playback_mode_type playback_mode;
193   char *cmd_start, *cmd_stop, *cmd_set_volume, *cmd_unfixable;
194   char *cmd_active_start, *cmd_active_stop;
195   int cmd_blocking, cmd_start_returns_output;
196   double tolerance; // allow this much drift before attempting to correct it
197   stuffing_type packet_stuffing;
198   int soxr_delay_index;
199   int soxr_delay_threshold; // the soxr delay must be less or equal to this for soxr interpolation
200                             // to be enabled under the auto setting
201   int decoders_supported;
202   int use_apple_decoder; // set to 1 if you want to use the apple decoder instead of the original by
203                          // David Hammerton
204   // char *logfile;
205   // char *errfile;
206   char *configfile;
207   char *regtype; // The regtype is the service type followed by the protocol, separated by a dot, by
208                  // default “_raop._tcp.”.
209   char *interface;     // a string containg the interface name, or NULL if nothing specified
210   int interface_index; // only valid if the interface string is non-NULL
211   double audio_backend_buffer_desired_length; // this will be the length in seconds of the
212                                               // audio backend buffer -- the DAC buffer for ALSA
213   double audio_backend_buffer_interpolation_threshold_in_seconds; // below this, soxr interpolation
214                                                                   // will not occur -- it'll be
215                                                                   // basic interpolation instead.
216   double disable_standby_mode_silence_threshold; // below this, silence will be added to the output
217                                                  // buffer
218   double disable_standby_mode_silence_scan_interval; // check the threshold this often
219 
220   double audio_backend_latency_offset; // this will be the offset in seconds to compensate for any
221                                        // fixed latency there might be in the audio path
222   int audio_backend_silent_lead_in_time_auto; // true if the lead-in time should be from as soon as
223                                               // packets are received
224   double audio_backend_silent_lead_in_time; // the length of the silence that should precede a play.
225   uint32_t minimum_free_buffer_headroom; // when effective latency is calculated, ensure this number
226                                          // of buffers are unallocated
227   double active_state_timeout; // the amount of time from when play ends to when the system leaves
228                                // into the "active" mode.
229   uint32_t volume_range_db; // the range, in dB, from max dB to min dB. Zero means use the mixer's
230                             // native range.
231   int volume_range_hw_priority; // when extending the volume range by combining sw and hw
232                                 // attenuators, lowering the volume, use all the hw attenuation
233                                 // before using
234                                 // sw attenuation
235   volume_control_profile_type volume_control_profile;
236 
237   int output_format_auto_requested; // true if the configuration requests auto configuration
238   sps_format_t output_format;
239   int output_rate_auto_requested; // true if the configuration requests auto configuration
240   unsigned int output_rate;
241 
242 #ifdef CONFIG_CONVOLUTION
243   int convolution;
244   int convolver_valid;
245   char *convolution_ir_file;
246   float convolution_gain;
247   int convolution_max_length;
248 #endif
249 
250   int loudness;
251   float loudness_reference_volume_db;
252   int alsa_use_hardware_mute;
253   double alsa_maximum_stall_time;
254   disable_standby_mode_type disable_standby_mode;
255   volatile int keep_dac_busy;
256   yna_type use_precision_timing; // defaults to no
257 
258 #if defined(CONFIG_DBUS_INTERFACE)
259   dbus_session_type dbus_service_bus_type;
260 #endif
261 #if defined(CONFIG_MPRIS_INTERFACE)
262   dbus_session_type mpris_service_bus_type;
263 #endif
264 
265 #ifdef CONFIG_METADATA_HUB
266   char *cover_art_cache_dir;
267   int retain_coverart;
268 
269   int scan_interval_when_active;   // number of seconds between DACP server scans when playing
270                                    // something (1)
271   int scan_interval_when_inactive; // number of seconds between DACP server scans playing nothing
272                                    // (3)
273   int scan_max_bad_response_count; // number of successive bad results to ignore before giving up
274                                    // (10)
275   int scan_max_inactive_count;     // number of scans to do before stopping if not made active again
276                                    // (about 15 minutes worth)
277 #endif
278   int disable_resend_requests; // set this to stop resend request being made for missing packets
279   double diagnostic_drop_packet_fraction; // pseudo randomly drop this fraction of packets, for
280                                           // debugging. Currently audio packets only...
281 #ifdef CONFIG_JACK
282   char *jack_client_name;
283   char *jack_autoconnect_pattern;
284 #ifdef CONFIG_SOXR
285   int jack_soxr_resample_quality;
286 #endif
287 #endif
288   void *gradients; // a linked list of the clock gradients discovered for all DACP IDs
289                    // can't use IP numbers as they might be given to different devices
290                    // can't get hold of MAC addresses.
291                    // can't define the nvll linked list struct here
292 } shairport_cfg;
293 
294 // accessors to config for multi-thread access
295 double get_config_airplay_volume();
296 void set_config_airplay_volume(double v);
297 
298 uint32_t nctohl(const uint8_t *p); // read 4 characters from *p and do ntohl on them
299 uint16_t nctohs(const uint8_t *p); // read 2 characters from *p and do ntohs on them
300 
301 void memory_barrier();
302 
303 void log_to_stderr(); // call this to direct logging to stderr;
304 void log_to_stdout(); // call this to direct logging to stdout;
305 void log_to_syslog(); // call this to direct logging to the system log;
306 void log_to_file();   // call this to direct logging to a file or (pre-existing) pipe;
307 
308 // true if Shairport Sync is supposed to be sending output to the output device, false otherwise
309 
310 int get_requested_connection_state_to_output();
311 
312 void set_requested_connection_state_to_output(int v);
313 
314 int try_to_open_pipe_for_writing(
315     const char *pathname); // open it without blocking if it's not hooked up
316 
317 /* from
318  * http://coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring#comment-722
319  */
320 char *str_replace(const char *string, const char *substr, const char *replacement);
321 
322 // based on http://burtleburtle.net/bob/rand/smallprng.html
323 
324 void r64init(uint64_t seed);
325 uint64_t r64u();
326 int64_t r64i();
327 
328 // if you are breaking in to a session, you need to avoid the ports of the current session
329 // if you are law-abiding, then you can reuse the ports.
330 // so, you can reset the free UDP ports minder when you're legit, and leave it otherwise
331 
332 // the downside of using different ports each time is that it might make the firewall
333 // rules a bit more complex, as they need to allow more than the minimum three ports.
334 // a range of 10 is suggested anyway
335 
336 void resetFreeUDPPort();
337 uint16_t nextFreeUDPPort();
338 
339 extern volatile int debuglev;
340 
341 void _die(const char *filename, const int linenumber, const char *format, ...);
342 void _warn(const char *filename, const int linenumber, const char *format, ...);
343 void _inform(const char *filename, const int linenumber, const char *format, ...);
344 void _debug(const char *filename, const int linenumber, int level, const char *format, ...);
345 
346 #define die(...) _die(__FILE__, __LINE__, __VA_ARGS__)
347 #define debug(...) _debug(__FILE__, __LINE__, __VA_ARGS__)
348 #define warn(...) _warn(__FILE__, __LINE__, __VA_ARGS__)
349 #define inform(...) _inform(__FILE__, __LINE__, __VA_ARGS__)
350 
351 uint8_t *base64_dec(char *input, int *outlen);
352 char *base64_enc(uint8_t *input, int length);
353 
354 #define RSA_MODE_AUTH (0)
355 #define RSA_MODE_KEY (1)
356 uint8_t *rsa_apply(uint8_t *input, int inlen, int *outlen, int mode);
357 
358 // given a volume (0 to -30) and high and low attenuations in dB*100 (e.g. 0 to -6000 for 0 to -60
359 // dB), return an attenuation depending on a linear interpolation along along the range
360 double flat_vol2attn(double vol, long max_db, long min_db);
361 
362 // given a volume (0 to -30) and high and low attenuations in dB*100 (e.g. 0 to -6000 for 0 to -60
363 // dB), return an attenuation depending on the transfer function
364 double vol2attn(double vol, long max_db, long min_db);
365 
366 // return a monolithic (always increasing) time in nanoseconds
367 // uint64_t get_absolute_time_in_fp(void); // obselete
368 uint64_t get_absolute_time_in_ns(void);
369 
370 // time at startup for debugging timing
371 extern uint64_t ns_time_at_startup, ns_time_at_last_debug_message;
372 
373 // this is for reading an unsigned 32 bit number, such as an RTP timestamp
374 
375 uint32_t uatoi(const char *nptr);
376 
377 // this is for allowing us to cancel the whole program
378 extern pthread_t main_thread_id;
379 
380 extern shairport_cfg config;
381 extern config_t config_file_stuff;
382 extern int emergency_exit;
383 
384 int config_set_lookup_bool(config_t *cfg, char *where, int *dst);
385 
386 void command_start(void);
387 void command_stop(void);
388 void command_execute(const char *command, const char *extra_argument, const int block);
389 void command_set_volume(double volume);
390 
391 int mkpath(const char *path, mode_t mode);
392 
393 void shairport_shutdown();
394 
395 extern sigset_t pselect_sigset;
396 
397 extern pthread_mutex_t the_conn_lock;
398 
399 #define conn_lock(arg)                                                                             \
400   pthread_mutex_lock(&the_conn_lock);                                                              \
401   arg;                                                                                             \
402   pthread_mutex_unlock(&the_conn_lock);
403 
404 // wait for the specified time in microseconds -- it checks every 20 milliseconds
405 int sps_pthread_mutex_timedlock(pthread_mutex_t *mutex, useconds_t dally_time,
406                                 const char *debugmessage, int debuglevel);
407 // wait for the specified time, checking every 20 milliseconds, and block if it can't acquire the
408 // lock
409 int _debug_mutex_lock(pthread_mutex_t *mutex, useconds_t dally_time, const char *mutexName,
410                       const char *filename, const int line, int debuglevel);
411 
412 #define debug_mutex_lock(mu, t, d) _debug_mutex_lock(mu, t, #mu, __FILE__, __LINE__, d)
413 
414 int _debug_mutex_unlock(pthread_mutex_t *mutex, const char *mutexName, const char *filename,
415                         const int line, int debuglevel);
416 
417 #define debug_mutex_unlock(mu, d) _debug_mutex_unlock(mu, #mu, __FILE__, __LINE__, d)
418 
419 void pthread_cleanup_debug_mutex_unlock(void *arg);
420 
421 #define pthread_cleanup_debug_mutex_lock(mu, t, d)                                                 \
422   if (_debug_mutex_lock(mu, t, #mu, __FILE__, __LINE__, d) == 0)                                   \
423   pthread_cleanup_push(pthread_cleanup_debug_mutex_unlock, (void *)mu)
424 
425 #define config_lock                                                                                \
426   if (pthread_mutex_trylock(&config.lock) != 0) {                                                  \
427     debug(1, "config_lock: cannot acquire config.lock");                                           \
428   }
429 
430 #define config_unlock pthread_mutex_unlock(&config.lock)
431 
432 extern pthread_mutex_t r64_mutex;
433 
434 #define r64_lock pthread_mutex_lock(&r64_mutex)
435 
436 #define r64_unlock pthread_mutex_unlock(&r64_mutex)
437 
438 char *get_version_string(); // mallocs a string space -- remember to free it afterwards
439 
440 int64_t generate_zero_frames(char *outp, size_t number_of_frames, sps_format_t format,
441                              int with_dither, int64_t random_number_in);
442 
443 void malloc_cleanup(void *arg);
444 
445 int string_update_with_size(char **str, int *flag, char *s, size_t len);
446 
447 // from https://stackoverflow.com/questions/13663617/memdup-function-in-c, with thanks
448 void *memdup(const void *mem, size_t size);
449 
450 #endif // _COMMON_H
451