forked from FDH2/UxPlay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uxplay.cpp
2273 lines (2115 loc) · 83.9 KB
/
uxplay.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* RPiPlay - An open-source AirPlay mirroring server for Raspberry Pi
* Copyright (C) 2019 Florian Draschbacher
* Modified extensively to become
* UxPlay - An open-souce AirPlay mirroring server.
* Modifications Copyright (C) 2021-23 F. Duncanh
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stddef.h>
#include <cstring>
#include <signal.h>
#include <unistd.h>
#include <ctype.h>
#include <string>
#include <algorithm>
#include <vector>
#include <fstream>
#include <sstream>
#include <iterator>
#include <sys/stat.h>
#include <cstdio>
#include <stdarg.h>
#include <math.h>
#ifdef _WIN32 /*modifications for Windows compilation */
#include <glib.h>
#include <unordered_map>
#include <winsock2.h>
#include <iphlpapi.h>
#else
#include <glib-unix.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <sys/types.h>
#include <pwd.h>
# ifdef __linux__
# include <netpacket/packet.h>
# else
# include <net/if_dl.h>
# endif
#endif
#include "lib/raop.h"
#include "lib/stream.h"
#include "lib/logger.h"
#include "lib/dnssd.h"
#include "renderers/video_renderer.h"
#include "renderers/audio_renderer.h"
#define VERSION "1.70"
#define SECOND_IN_USECS 1000000
#define SECOND_IN_NSECS 1000000000UL
#define DEFAULT_NAME "UxPlay"
#define DEFAULT_DEBUG_LOG false
#define LOWEST_ALLOWED_PORT 1024
#define HIGHEST_PORT 65535
#define NTP_TIMEOUT_LIMIT 5
#define BT709_FIX "capssetter caps=\"video/x-h264, colorimetry=bt709\""
static std::string server_name = DEFAULT_NAME;
static dnssd_t *dnssd = NULL;
static raop_t *raop = NULL;
static logger_t *render_logger = NULL;
static bool audio_sync = false;
static bool video_sync = true;
static int64_t audio_delay_alac = 0;
static int64_t audio_delay_aac = 0;
static bool relaunch_video = false;
static bool reset_loop = false;
static unsigned int open_connections= 0;
static std::string videosink = "autovideosink";
static std::string videosink_options = "";
static videoflip_t videoflip[2] = { NONE , NONE };
static bool use_video = true;
static unsigned char compression_type = 0;
static std::string audiosink = "autoaudiosink";
static int audiodelay = -1;
static bool use_audio = true;
static bool new_window_closing_behavior = true;
static bool close_window;
static std::string video_parser = "h264parse";
static std::string video_decoder = "decodebin";
static std::string video_converter = "videoconvert";
static bool show_client_FPS_data = false;
static unsigned int max_ntp_timeouts = NTP_TIMEOUT_LIMIT;
static FILE *video_dumpfile = NULL;
static std::string video_dumpfile_name = "videodump";
static int video_dump_limit = 0;
static int video_dumpfile_count = 0;
static int video_dump_count = 0;
static bool dump_video = false;
static unsigned char mark[] = { 0x00, 0x00, 0x00, 0x01 };
static FILE *audio_dumpfile = NULL;
static std::string audio_dumpfile_name = "audiodump";
static int audio_dump_limit = 0;
static int audio_dumpfile_count = 0;
static int audio_dump_count = 0;
static bool dump_audio = false;
static unsigned char audio_type = 0x00;
static unsigned char previous_audio_type = 0x00;
static bool fullscreen = false;
static std::string coverart_filename = "";
static bool do_append_hostname = true;
static bool use_random_hw_addr = false;
static unsigned short display[5] = {0}, tcp[3] = {0}, udp[3] = {0};
static bool debug_log = DEFAULT_DEBUG_LOG;
static int log_level = LOGGER_INFO;
static bool bt709_fix = false;
static int nohold = 0;
static bool nofreeze = false;
static unsigned short raop_port;
static unsigned short airplay_port;
static uint64_t remote_clock_offset = 0;
static std::vector<std::string> allowed_clients;
static std::vector<std::string> blocked_clients;
static bool restrict_clients;
static bool setup_legacy_pairing = false;
static bool require_password = false;
static unsigned short pin = 0;
static std::string keyfile = "";
static std::string mac_address = "";
static std::string dacpfile = "";
static bool registration_list = false;
static std::string pairing_register = "";
static std::vector <std::string> registered_keys;
static double db_low = -30.0;
static double db_high = 0.0;
static bool taper_volume = false;
static bool h265_support = false;
static int n_renderers = 0;
/* logging */
static void log(int level, const char* format, ...) {
va_list vargs;
if (level > log_level) return;
switch (level) {
case 0:
case 1:
case 2:
case 3:
printf("*** ERROR: ");
break;
case 4:
printf("*** WARNING: ");
break;
default:
break;
}
va_start(vargs, format);
vprintf(format, vargs);
printf("\n");
va_end(vargs);
}
#define LOGD(...) log(LOGGER_DEBUG, __VA_ARGS__)
#define LOGI(...) log(LOGGER_INFO, __VA_ARGS__)
#define LOGW(...) log(LOGGER_WARNING, __VA_ARGS__)
#define LOGE(...) log(LOGGER_ERR, __VA_ARGS__)
static bool file_has_write_access (const char * filename) {
bool exists = false;
bool write = false;
#ifdef _WIN32
if ((exists = _access(filename, 0) != -1)) {
write = (_access(filename, 2) != -1);
}
#else
if ((exists = access(filename, F_OK) != -1)) {
write = (access(filename, W_OK) != -1);
}
#endif
if (!exists) {
FILE *fp = fopen(filename, "w");
if (fp) {
write = true;
fclose(fp);
remove(filename);
}
}
return write;
}
/* 95 byte png file with a 1x1 white square (single pixel): placeholder for coverart*/
static const unsigned char empty_image[] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25, 0xdb, 0x56,
0xca, 0x00, 0x00, 0x00, 0x03, 0x50, 0x4c, 0x54, 0x45, 0x00, 0x00, 0x00, 0xa7, 0x7a, 0x3d, 0xda,
0x00, 0x00, 0x00, 0x01, 0x74, 0x52, 0x4e, 0x53, 0x00, 0x40, 0xe6, 0xd8, 0x66, 0x00, 0x00, 0x00,
0x0a, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2,
0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 };
static size_t write_coverart(const char *filename, const void *image, size_t len) {
FILE *fp = fopen(filename, "wb");
size_t count = fwrite(image, 1, len, fp);
fclose(fp);
return count;
}
static char *create_pin_display(char *pin_str, int margin, int gap) {
char *ptr;
char num[2] = { 0 };
int w = 10;
int h = 8;
char digits[10][8][11] = { "0821111380", "2114005113", "1110000111", "1110000111", "1110000111", "1110000111", "5113002114", "0751111470",
"0002111000", "0021111000", "0000111000", "0000111000", "0000111000", "0000111000", "0000111000", "0011111110",
"0811112800", "2114005113", "0000000111", "0000082114", "0862111470", "2114700000", "1117000000", "1111111111",
"0821111380", "2114005113", "0000082114", "0000111170", "0000075130", "1110000111", "5113002114", "0751111470",
"0000211110", "0001401110", "0021401110", "0214001110", "2110001110", "1111111111", "0000001110", "0000001110",
"1111111110", "1110000000", "1110000000", "1112111380", "0000075113", "0000000111", "5113002114", "0711114700",
"0821111380", "2114005113", "1110000000", "1112111380", "1114075113", "1110000111", "5113002114", "0751111470",
"1111111111", "0000002114", "0000021140", "0000211400", "0002114000", "0021140000", "0211400000", "2114000000",
"0831111280", "2114002114", "5113802114", "0751111170", "8214775138", "1110000111", "5113002114", "0751111470",
"0821111380", "2114005113", "1110000111", "5113802111", "0751114111", "0000000111", "5113002114", "0751111470"
};
char pixels[9] = { ' ', '8', 'd', 'b', 'P', 'Y', 'o', '"', '.' };
/* Ascii art used here is derived from the FIGlet font "collosal" */
int pin_val = (int) strtoul(pin_str, &ptr, 10);
if (*ptr) {
return NULL;
}
int len = strlen(pin_str);
int *pin = (int *) calloc( len, sizeof(int));
if(!pin) {
return NULL;
}
for (int i = 0; i < len; i++) {
pin[len - 1 - i] = pin_val % 10;
pin_val = pin_val / 10;
}
int size = 4 + h*(margin + len*(w + gap + 1));
char *pin_image = (char *) calloc(size, sizeof(char));
if (!pin_image) {
return NULL;
}
char *pos = pin_image;
snprintf(pos, 2, "\n");
pos++;
for (int i = 0; i < h; i++) {
for (int j = 0; j < margin; j++) {
snprintf(pos, 2, " ");
pos++;
}
for (int j = 0; j < len; j++) {
int l = pin[j];
char *p = digits[l][i];
for (int k = 0; k < w; k++) {
char *ptr;
strncpy(num, p++, 1);
int r = (int) strtoul(num, &ptr, 10);
snprintf(pos, 2, "%c", pixels[r]);
pos++;
}
for (int n=0; n < gap ; n++) {
snprintf(pos, 2, " ");
pos++;
}
}
snprintf(pos, 2, "\n");
pos++;
}
snprintf(pos, 2, "\n");
return pin_image;
}
static void dump_audio_to_file(unsigned char *data, int datalen, unsigned char type) {
if (!audio_dumpfile && audio_type != previous_audio_type) {
char suffix[20];
std::string fn = audio_dumpfile_name;
previous_audio_type = audio_type;
audio_dumpfile_count++;
audio_dump_count = 0;
/* type 0x20 is lossless ALAC, type 0x80 is compressed AAC-ELD, type 0x10 is "other" */
if (audio_type == 0x20) {
snprintf(suffix, sizeof(suffix), ".%d.alac", audio_dumpfile_count);
} else if (audio_type == 0x80) {
snprintf(suffix, sizeof(suffix), ".%d.aac", audio_dumpfile_count);
} else {
snprintf(suffix, sizeof(suffix), ".%d.aud", audio_dumpfile_count);
}
fn.append(suffix);
audio_dumpfile = fopen(fn.c_str(),"w");
if (audio_dumpfile == NULL) {
LOGE("could not open file %s for dumping audio frames",fn.c_str());
}
}
if (audio_dumpfile) {
fwrite(data, 1, datalen, audio_dumpfile);
if (audio_dump_limit) {
audio_dump_count++;
if (audio_dump_count == audio_dump_limit) {
fclose(audio_dumpfile);
audio_dumpfile = NULL;
}
}
}
}
static void dump_video_to_file(unsigned char *data, int datalen) {
/* SPS NAL has (data[4] & 0x1f) = 0x07 */
if ((data[4] & 0x1f) == 0x07 && video_dumpfile && video_dump_limit) {
fwrite(mark, 1, sizeof(mark), video_dumpfile);
fclose(video_dumpfile);
video_dumpfile = NULL;
video_dump_count = 0;
}
if (!video_dumpfile) {
std::string fn = video_dumpfile_name;
if (video_dump_limit) {
char suffix[20];
video_dumpfile_count++;
snprintf(suffix, sizeof(suffix), ".%d", video_dumpfile_count);
fn.append(suffix);
}
fn.append(".h264");
video_dumpfile = fopen (fn.c_str(),"w");
if (video_dumpfile == NULL) {
LOGE("could not open file %s for dumping h264 frames",fn.c_str());
}
}
if (video_dumpfile) {
if (video_dump_limit == 0) {
fwrite(data, 1, datalen, video_dumpfile);
} else if (video_dump_count < video_dump_limit) {
video_dump_count++;
fwrite(data, 1, datalen, video_dumpfile);
}
}
}
static gboolean reset_callback(gpointer loop) {
if (reset_loop) {
g_main_loop_quit((GMainLoop *) loop);
}
return TRUE;
}
static gboolean sigint_callback(gpointer loop) {
relaunch_video = false;
g_main_loop_quit((GMainLoop *) loop);
return TRUE;
}
static gboolean sigterm_callback(gpointer loop) {
relaunch_video = false;
g_main_loop_quit((GMainLoop *) loop);
return TRUE;
}
#ifdef _WIN32
struct signal_handler {
GSourceFunc handler;
gpointer user_data;
};
static std::unordered_map<gint, signal_handler> u = {};
static void SignalHandler(int signum) {
if (signum == SIGTERM || signum == SIGINT) {
u[signum].handler(u[signum].user_data);
}
}
static guint g_unix_signal_add(gint signum, GSourceFunc handler, gpointer user_data) {
u[signum] = signal_handler{handler, user_data};
(void) signal(signum, SignalHandler);
return 0;
}
#endif
static void main_loop() {
guint gst_bus_watch_id[2] = { 0 };
g_assert(n_renderers <= 2);
GMainLoop *loop = g_main_loop_new(NULL,FALSE);
relaunch_video = false;
if (use_video) {
relaunch_video = true;
for (int i = 0; i < n_renderers; i++) {
gst_bus_watch_id[i] = (guint) video_renderer_listen((void *)loop, i);
}
}
guint reset_watch_id = g_timeout_add(100, (GSourceFunc) reset_callback, (gpointer) loop);
guint video_reset_watch_id = g_timeout_add(100, (GSourceFunc) video_reset_callback, (gpointer) loop);
guint sigterm_watch_id = g_unix_signal_add(SIGTERM, (GSourceFunc) sigterm_callback, (gpointer) loop);
guint sigint_watch_id = g_unix_signal_add(SIGINT, (GSourceFunc) sigint_callback, (gpointer) loop);
//printf("********** main_loop_run *******************\n");
g_main_loop_run(loop);
//printf("********** main_loop_exit *******************\n");
for (int i = 0; i < n_renderers; i++) {
if (gst_bus_watch_id[i] > 0) g_source_remove(gst_bus_watch_id[i]);
}
if (sigint_watch_id > 0) g_source_remove(sigint_watch_id);
if (sigterm_watch_id > 0) g_source_remove(sigterm_watch_id);
if (reset_watch_id > 0) g_source_remove(reset_watch_id);
if (video_reset_watch_id > 0) g_source_remove(video_reset_watch_id);
g_main_loop_unref(loop);
}
static int parse_hw_addr (std::string str, std::vector<char> &hw_addr) {
for (int i = 0; i < (int) str.length(); i += 3) {
hw_addr.push_back((char) stol(str.substr(i), NULL, 16));
}
return 0;
}
static const char *get_homedir() {
const char *homedir = getenv("XDG_CONFIG_HOMEDIR");
if (homedir == NULL) {
homedir = getenv("HOME");
}
#ifndef _WIN32
if (homedir == NULL){
homedir = getpwuid(getuid())->pw_dir;
}
#endif
return homedir;
}
static std::string find_uxplay_config_file() {
std::string no_config_file = "";
const char *homedir = NULL;
const char *uxplayrc = NULL;
std::string config0, config1, config2;
struct stat sb;
uxplayrc = getenv("UXPLAYRC"); /* first look for $UXPLAYRC */
if (uxplayrc) {
config0 = uxplayrc;
if (stat(config0.c_str(), &sb) == 0) return config0;
}
homedir = get_homedir();
if (homedir) {
config1 = homedir;
config1.append("/.uxplayrc");
if (stat(config1.c_str(), &sb) == 0) return config1; /* look for ~/.uxplayrc */
config2 = homedir;
config2.append("/.config/uxplayrc"); /* look for ~/.config/uxplayrc */
if (stat(config2.c_str(), &sb) == 0) return config2;
}
return no_config_file;
}
static std::string find_mac () {
/* finds the MAC address of a network interface *
* in a Windows, Linux, *BSD or macOS system. */
std::string mac = "";
char str[3];
#ifdef _WIN32
ULONG buflen = sizeof(IP_ADAPTER_ADDRESSES);
PIP_ADAPTER_ADDRESSES addresses = (IP_ADAPTER_ADDRESSES*) malloc(buflen);
if (addresses == NULL) {
return mac;
}
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, addresses, &buflen) == ERROR_BUFFER_OVERFLOW) {
free(addresses);
addresses = (IP_ADAPTER_ADDRESSES*) malloc(buflen);
if (addresses == NULL) {
return mac;
}
}
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, addresses, &buflen) == NO_ERROR) {
for (PIP_ADAPTER_ADDRESSES address = addresses; address != NULL; address = address->Next) {
if (address->PhysicalAddressLength != 6 /* MAC has 6 octets */
|| (address->IfType != 6 && address->IfType != 71) /* Ethernet or Wireless interface */
|| address->OperStatus != 1) { /* interface is up */
continue;
}
mac.erase();
for (int i = 0; i < 6; i++) {
snprintf(str, sizeof(str), "%02x", int(address->PhysicalAddress[i]));
mac = mac + str;
if (i < 5) mac = mac + ":";
}
break;
}
}
free(addresses);
return mac;
#else
struct ifaddrs *ifap, *ifaptr;
int non_null_octets = 0;
unsigned char octet[6];
if (getifaddrs(&ifap) == 0) {
for(ifaptr = ifap; ifaptr != NULL; ifaptr = ifaptr->ifa_next) {
if(ifaptr->ifa_addr == NULL) continue;
#ifdef __linux__
if (ifaptr->ifa_addr->sa_family != AF_PACKET) continue;
struct sockaddr_ll *s = (struct sockaddr_ll*) ifaptr->ifa_addr;
for (int i = 0; i < 6; i++) {
if ((octet[i] = s->sll_addr[i]) != 0) non_null_octets++;
}
#else /* macOS and *BSD */
if (ifaptr->ifa_addr->sa_family != AF_LINK) continue;
unsigned char *ptr = (unsigned char *) LLADDR((struct sockaddr_dl *) ifaptr->ifa_addr);
for (int i= 0; i < 6 ; i++) {
if ((octet[i] = *ptr) != 0) non_null_octets++;
ptr++;
}
#endif
if (non_null_octets) {
mac.erase();
for (int i = 0; i < 6 ; i++) {
snprintf(str, sizeof(str), "%02x", octet[i]);
mac = mac + str;
if (i < 5) mac = mac + ":";
}
break;
}
}
}
freeifaddrs(ifap);
#endif
return mac;
}
#define MULTICAST 0
#define LOCAL 1
#define OCTETS 6
static bool validate_mac(char * mac_address) {
char c;
if (strlen(mac_address) != 17) return false;
for (int i = 0; i < 17; i++) {
c = *(mac_address + i);
if (i % 3 == 2) {
if (c != ':') return false;
} else {
if (c < '0') return false;
if (c > '9' && c < 'A') return false;
if (c > 'F' && c < 'a') return false;
if (c > 'f') return false;
}
}
return true;
}
static std::string random_mac () {
char str[3];
int octet = rand() % 64;
octet = (octet << 1) + LOCAL;
octet = (octet << 1) + MULTICAST;
snprintf(str,3,"%02x",octet);
std::string mac_address(str);
for (int i = 1; i < OCTETS; i++) {
mac_address = mac_address + ":";
octet = rand() % 256;
snprintf(str,3,"%02x",octet);
mac_address = mac_address + str;
}
return mac_address;
}
static void print_info (char *name) {
printf("UxPlay %s: An open-source AirPlay mirroring server.\n", VERSION);
printf("=========== Website: https://github.com/FDH2/UxPlay ==========\n");
printf("Usage: %s [-n name] [-s wxh] [-p [n]] [(other options)]\n", name);
printf("Options:\n");
printf("-n name Specify the network name of the AirPlay server\n");
printf("-nh Do not add \"@hostname\" at the end of AirPlay server name\n");
printf("-h265 Support h265 (4K) video (with h265 versions of h264 plugins)\n");
printf("-pin[xxxx]Use a 4-digit pin code to control client access (default: no)\n");
printf(" default pin is random: optionally use fixed pin xxxx\n");
printf("-reg [fn] Keep a register in $HOME/.uxplay.register to verify returning\n");
printf(" client pin-registration; (option: use file \"fn\" for this)\n");
printf("-vsync [x]Mirror mode: sync audio to video using timestamps (default)\n");
printf(" x is optional audio delay: millisecs, decimal, can be neg.\n");
printf("-vsync no Switch off audio/(server)video timestamp synchronization \n");
printf("-async [x]Audio-Only mode: sync audio to client video (default: no)\n");
printf("-async no Switch off audio/(client)video timestamp synchronization\n");
printf("-db l[:h] Set minimum volume attenuation to l dB (decibels, negative);\n");
printf(" optional: set maximum to h dB (+ or -) default: -30.0:0.0 dB\n");
printf("-taper Use a \"tapered\" AirPlay volume-control profile\n");
printf("-s wxh[@r]Request to client for video display resolution [refresh_rate]\n");
printf(" default 1920x1080[@60] (or 3840x2160[@60] with -h265 option)\n");
printf("-o Set display \"overscanned\" mode on (not usually needed)\n");
printf("-fs Full-screen (only works with X11, Wayland, VAAPI, D3D11)\n");
printf("-p Use legacy ports UDP 6000:6001:7011 TCP 7000:7001:7100\n");
printf("-p n Use TCP and UDP ports n,n+1,n+2. range %d-%d\n", LOWEST_ALLOWED_PORT, HIGHEST_PORT);
printf(" use \"-p n1,n2,n3\" to set each port, \"n1,n2\" for n3 = n2+1\n");
printf(" \"-p tcp n\" or \"-p udp n\" sets TCP or UDP ports separately\n");
printf("-avdec Force software h264 video decoding with libav decoder\n");
printf("-vp ... Choose the GSteamer h264 parser: default \"h264parse\"\n");
printf("-vd ... Choose the GStreamer h264 decoder; default \"decodebin\"\n");
printf(" choices: (software) avdec_h264; (hardware) v4l2h264dec,\n");
printf(" nvdec, nvh264dec, vaapih64dec, vtdec,etc.\n");
printf("-vc ... Choose the GStreamer videoconverter; default \"videoconvert\"\n");
printf(" another choice when using v4l2h264dec: v4l2convert\n");
printf("-vs ... Choose the GStreamer videosink; default \"autovideosink\"\n");
printf(" some choices: ximagesink,xvimagesink,vaapisink,glimagesink,\n");
printf(" gtksink,waylandsink,osxvideosink,kmssink,d3d11videosink etc.\n");
printf("-vs 0 Streamed audio only, with no video display window\n");
printf("-v4l2 Use Video4Linux2 for GPU hardware h264 decoding\n");
printf("-bt709 Sometimes needed for Raspberry Pi with GStreamer < 1.22 \n");
printf("-as ... Choose the GStreamer audiosink; default \"autoaudiosink\"\n");
printf(" some choices:pulsesink,alsasink,pipewiresink,jackaudiosink,\n");
printf(" osssink,oss4sink,osxaudiosink,wasapisink,directsoundsink.\n");
printf("-as 0 (or -a) Turn audio off, streamed video only\n");
printf("-al x Audio latency in seconds (default 0.25) reported to client.\n");
printf("-ca <fn> In Airplay Audio (ALAC) mode, write cover-art to file <fn>\n");
printf("-reset n Reset after 3n seconds client silence (default %d, 0=never)\n", NTP_TIMEOUT_LIMIT);
printf("-nofreeze Do NOT leave frozen screen in place after reset\n");
printf("-nc Do NOT Close video window when client stops mirroring\n");
printf("-nohold Drop current connection when new client connects.\n");
printf("-restrict Restrict clients to those specified by \"-allow <deviceID>\"\n");
printf(" UxPlay displays deviceID when a client attempts to connect\n");
printf(" Use \"-restrict no\" for no client restrictions (default)\n");
printf("-allow <i>Permit deviceID = <i> to connect if restrictions are imposed\n");
printf("-block <i>Always block connections from deviceID = <i>\n");
printf("-FPSdata Show video-streaming performance reports sent by client.\n");
printf("-fps n Set maximum allowed streaming framerate, default 30\n");
printf("-f {H|V|I}Horizontal|Vertical flip, or both=Inversion=rotate 180 deg\n");
printf("-r {R|L} Rotate 90 degrees Right (cw) or Left (ccw)\n");
printf("-m [mac] Set MAC address (also Device ID);use for concurrent UxPlays\n");
printf(" if mac xx:xx:xx:xx:xx:xx is not given, a random MAC is used\n");
printf("-key [fn] Store private key in $HOME/.uxplay.pem (or in file \"fn\")\n");
printf("-dacp [fn]Export client DACP information to file $HOME/.uxplay.dacp\n");
printf(" (option to use file \"fn\" instead); used for client remote\n");
printf("-vdmp [n] Dump h264 video output to \"fn.h264\"; fn=\"videodump\",change\n");
printf(" with \"-vdmp [n] filename\". If [n] is given, file fn.x.h264\n");
printf(" x=1,2,.. opens whenever a new SPS/PPS NAL arrives, and <=n\n");
printf(" NAL units are dumped.\n");
printf("-admp [n] Dump audio output to \"fn.x.fmt\", fmt ={aac, alac, aud}, x\n");
printf(" =1,2,..; fn=\"audiodump\"; change with \"-admp [n] filename\".\n");
printf(" x increases when audio format changes. If n is given, <= n\n");
printf(" audio packets are dumped. \"aud\"= unknown format.\n");
printf("-d Enable debug logging\n");
printf("-v Displays version information\n");
printf("-h Displays this help\n");
printf("Startup options in $UXPLAYRC, ~/.uxplayrc, or ~/.config/uxplayrc are\n");
printf("applied first (command-line options may modify them): format is one \n");
printf("option per line, no initial \"-\"; lines starting with \"#\" are ignored.\n");
}
static bool option_has_value(const int i, const int argc, std::string option, const char *next_arg) {
if (i >= argc - 1 || next_arg[0] == '-') {
LOGE("invalid: \"%s\" had no argument", option.c_str());
return false;
}
return true;
}
static bool get_display_settings (std::string value, unsigned short *w, unsigned short *h, unsigned short *r) {
// assume str = wxh@r is valid if w and h are positive decimal integers
// with no more than 4 digits, r < 256 (stored in one byte).
char *end;
std::size_t pos = value.find_first_of("x");
if (pos == std::string::npos) return false;
std::string str1 = value.substr(pos+1);
value.erase(pos);
if (value.length() == 0 || value.length() > 4 || value[0] == '-') return false;
*w = (unsigned short) strtoul(value.c_str(), &end, 10);
if (*end || *w == 0) return false;
pos = str1.find_first_of("@");
if(pos != std::string::npos) {
std::string str2 = str1.substr(pos+1);
if (str2.length() == 0 || str2.length() > 3 || str2[0] == '-') return false;
*r = (unsigned short) strtoul(str2.c_str(), &end, 10);
if (*end || *r == 0 || *r > 255) return false;
str1.erase(pos);
}
if (str1.length() == 0 || str1.length() > 4 || str1[0] == '-') return false;
*h = (unsigned short) strtoul(str1.c_str(), &end, 10);
if (*end || *h == 0) return false;
return true;
}
static bool get_value (const char *str, unsigned int *n) {
// if n > 0 str must be a positive decimal <= input value *n
// if n = 0, str must be a non-negative decimal
if (strlen(str) == 0 || strlen(str) > 10 || str[0] == '-') return false;
char *end;
unsigned long l = strtoul(str, &end, 10);
if (*end) return false;
if (*n && (l == 0 || l > *n)) return false;
*n = (unsigned int) l;
return true;
}
static bool get_ports (int nports, std::string option, const char * value, unsigned short * const port) {
/*valid entries are comma-separated values port_1,port_2,...,port_r, 0 < r <= nports */
/*where ports are distinct, and are in the allowed range. */
/*missing values are consecutive to last given value (at least one value needed). */
char *end;
unsigned long l;
std::size_t pos;
std::string val(value), str;
for (int i = 0; i <= nports ; i++) {
if(i == nports) break;
pos = val.find_first_of(',');
str = val.substr(0,pos);
if(str.length() == 0 || str.length() > 5 || str[0] == '-') break;
l = strtoul(str.c_str(), &end, 10);
if (*end || l < LOWEST_ALLOWED_PORT || l > HIGHEST_PORT) break;
*(port + i) = (unsigned short) l;
for (int j = 0; j < i ; j++) {
if( *(port + j) == *(port + i)) break;
}
if(pos == std::string::npos) {
if (nports + *(port + i) > i + 1 + HIGHEST_PORT) break;
for (int j = i + 1; j < nports; j++) {
*(port + j) = *(port + j - 1) + 1;
}
return true;
}
val.erase(0, pos+1);
}
LOGE("invalid \"%s %s\", all %d ports must be in range [%d,%d]",
option.c_str(), value, nports, LOWEST_ALLOWED_PORT, HIGHEST_PORT);
return false;
}
static bool get_videoflip (const char *str, videoflip_t *videoflip) {
if (strlen(str) > 1) return false;
switch (str[0]) {
case 'I':
*videoflip = INVERT;
break;
case 'H':
*videoflip = HFLIP;
break;
case 'V':
*videoflip = VFLIP;
break;
default:
return false;
}
return true;
}
static bool get_videorotate (const char *str, videoflip_t *videoflip) {
if (strlen(str) > 1) return false;
switch (str[0]) {
case 'L':
*videoflip = LEFT;
break;
case 'R':
*videoflip = RIGHT;
break;
default:
return false;
}
return true;
}
static void append_hostname(std::string &server_name) {
#ifdef _WIN32 /*modification for compilation on Windows */
char buffer[256] = "";
unsigned long size = sizeof(buffer);
if (GetComputerNameA(buffer, &size)) {
std::string name = server_name;
name.append("@");
name.append(buffer);
server_name = name;
}
#else
struct utsname buf;
if (!uname(&buf)) {
std::string name = server_name;
name.append("@");
name.append(buf.nodename);
server_name = name;
}
#endif
}
static void parse_arguments (int argc, char *argv[]) {
// Parse arguments
for (int i = 1; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "-allow") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
i++;
allowed_clients.push_back(argv[i]);
} else if (arg == "-block") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
i++;
blocked_clients.push_back(argv[i]);
} else if (arg == "-restrict") {
if (i < argc - 1) {
if (strlen(argv[i+1]) == 2 && strncmp(argv[i+1], "no", 2) == 0) {
restrict_clients = false;
i++;
continue;
}
}
restrict_clients = true;
} else if (arg == "-n") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
server_name = std::string(argv[++i]);
} else if (arg == "-nh") {
do_append_hostname = false;
} else if (arg == "-async") {
audio_sync = true;
if (i < argc - 1) {
if (strlen(argv[i+1]) == 2 && strncmp(argv[i+1], "no", 2) == 0) {
audio_sync = false;
i++;
continue;
}
char *end;
int n = (int) (strtof(argv[i + 1], &end) * 1000);
if (*end == '\0') {
i++;
if (n > -SECOND_IN_USECS && n < SECOND_IN_USECS) {
audio_delay_alac = n * 1000; /* units are nsecs */
} else {
fprintf(stderr, "invalid -async %s: requested delays must be smaller than +/- 1000 millisecs\n", argv[i] );
exit (1);
}
}
}
} else if (arg == "-vsync") {
video_sync = true;
if (i < argc - 1) {
if (strlen(argv[i+1]) == 2 && strncmp(argv[i+1], "no", 2) == 0) {
video_sync = false;
i++;
continue;
}
char *end;
int n = (int) (strtof(argv[i + 1], &end) * 1000);
if (*end == '\0') {
i++;
if (n > -SECOND_IN_USECS && n < SECOND_IN_USECS) {
audio_delay_aac = n * 1000; /* units are nsecs */
} else {
fprintf(stderr, "invalid -vsync %s: requested delays must be smaller than +/- 1000 millisecs\n", argv[i]);
exit (1);
}
}
}
} else if (arg == "-s") {
if (!option_has_value(i, argc, argv[i], argv[i+1])) exit(1);
std::string value(argv[++i]);
if (!get_display_settings(value, &display[0], &display[1], &display[2])) {
fprintf(stderr, "invalid \"-s %s\"; -s wxh : max w,h=9999; -s wxh@r : max r=255\n",
argv[i]);
exit(1);
}
} else if (arg == "-fps") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
unsigned int n = 255;
if (!get_value(argv[++i], &n)) {
fprintf(stderr, "invalid \"-fps %s\"; -fps n : max n=255, default n=30\n", argv[i]);
exit(1);
}
display[3] = (unsigned short) n;
} else if (arg == "-o") {
display[4] = 1;
} else if (arg == "-f") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
if (!get_videoflip(argv[++i], &videoflip[0])) {
fprintf(stderr,"invalid \"-f %s\" , unknown flip type, choices are H, V, I\n",argv[i]);
exit(1);
}
} else if (arg == "-r") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
if (!get_videorotate(argv[++i], &videoflip[1])) {
fprintf(stderr,"invalid \"-r %s\" , unknown rotation type, choices are R, L\n",argv[i]);
exit(1);
}
} else if (arg == "-p") {
if (i == argc - 1 || argv[i + 1][0] == '-') {
tcp[0] = 7100; tcp[1] = 7000; tcp[2] = 7001;
udp[0] = 7011; udp[1] = 6001; udp[2] = 6000;
continue;
}
std::string value(argv[++i]);
if (value == "tcp") {
arg.append(" tcp");
if(!get_ports(3, arg, argv[++i], tcp)) exit(1);
} else if (value == "udp") {
arg.append( " udp");
if(!get_ports(3, arg, argv[++i], udp)) exit(1);
} else {
if(!get_ports(3, arg, argv[i], tcp)) exit(1);
for (int j = 1; j < 3; j++) {
udp[j] = tcp[j];
}
}
} else if (arg == "-m") {
if (i < argc - 1 && *argv[i+1] != '-') {
if (validate_mac(argv[++i])) {
mac_address.erase();
mac_address = argv[i];
use_random_hw_addr = false;
} else {
fprintf(stderr,"invalid mac address \"%s\": address must have form"
" \"xx:xx:xx:xx:xx:xx\", x = 0-9, A-F or a-f\n", argv[i]);
exit(1);
}
} else {
use_random_hw_addr = true;
}
} else if (arg == "-a") {
use_audio = false;
} else if (arg == "-d") {
debug_log = !debug_log;
} else if (arg == "-h" || arg == "--help" || arg == "-?" || arg == "-help") {
print_info(argv[0]);
exit(0);
} else if (arg == "-v") {
printf("UxPlay version %s; for help, use option \"-h\"\n", VERSION);
exit(0);
} else if (arg == "-vp") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
video_parser.erase();
video_parser.append(argv[++i]);
} else if (arg == "-vd") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
video_decoder.erase();
video_decoder.append(argv[++i]);
} else if (arg == "-vc") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
video_converter.erase();
video_converter.append(argv[++i]);
} else if (arg == "-vs") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
videosink.erase();
videosink.append(argv[++i]);
std::size_t pos = videosink.find(" ");
if (pos != std::string::npos) {
videosink_options.erase();
videosink_options = videosink.substr(pos);
videosink.erase(pos);
}
} else if (arg == "-as") {
if (!option_has_value(i, argc, arg, argv[i+1])) exit(1);
audiosink.erase();
audiosink.append(argv[++i]);
} else if (arg == "-t") {
fprintf(stderr,"The uxplay option \"-t\" has been removed: it was a workaround for an Avahi issue.\n");
fprintf(stderr,"The correct solution is to open network port UDP 5353 in the firewall for mDNS queries\n");
exit(1);
} else if (arg == "-nc") {
new_window_closing_behavior = false;
} else if (arg == "-avdec") {
video_parser.erase();
video_parser = "h264parse";
video_decoder.erase();
video_decoder = "avdec_h264";
video_converter.erase();
video_converter = "videoconvert";
} else if (arg == "-v4l2") {
video_decoder.erase();
video_decoder = "v4l2h264dec";
video_converter.erase();
video_converter = "v4l2convert";
} else if (arg == "-rpi" || arg == "-rpifb" || arg == "-rpigl" || arg == "-rpiwl") {
fprintf(stderr,"*** -rpi* options do not apply to Raspberry Pi model 5, and have been removed\n");
fprintf(stderr," For models 3 and 4, use their equivalents, if needed:\n");
fprintf(stderr," -rpi was equivalent to \"-v4l2\"\n");
fprintf(stderr," -rpifb was equivalent to \"-v4l2 -vs kmssink\"\n");
fprintf(stderr," -rpigl was equivalent to \"-v4l2 -vs glimagesink\"\n");
fprintf(stderr," -rpiwl was equivalent to \"-v4l2 -vs waylandsink\"\n");
fprintf(stderr," for GStreamer < 1.22, \"-bt709\" may also be needed\n");
exit(1);
} else if (arg == "-fs" ) {
fullscreen = true;
} else if (arg == "-FPSdata") {
show_client_FPS_data = true;
} else if (arg == "-reset") {
max_ntp_timeouts = 0;
if (!get_value(argv[++i], &max_ntp_timeouts)) {
fprintf(stderr, "invalid \"-reset %s\"; -reset n must have n >= 0, default n = %d\n", argv[i], NTP_TIMEOUT_LIMIT);
exit(1);
}
} else if (arg == "-vdmp") {
dump_video = true;
if (i < argc - 1 && *argv[i+1] != '-') {
unsigned int n = 0;
if (get_value (argv[++i], &n)) {
if (n == 0) {
fprintf(stderr, "invalid \"-vdmp 0 %s\"; -vdmp n needs a non-zero value of n\n", argv[i]);
exit(1);
}