forked from antimof/UxPlay
-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathuxplay.cpp
More file actions
3326 lines (3110 loc) · 125 KB
/
uxplay.cpp
File metadata and controls
3326 lines (3110 loc) · 125 KB
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 <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>
#include <inttypes.h>
#ifdef _WIN32 /*modifications for Windows compilation */
#include <glib.h>
#include <unordered_map>
#include <winsock2.h>
#include <iphlpapi.h>
#include <pthread.h> //for pthreads in MSYS2 UCRT
#else
#include <csignal>
#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>
# ifdef __OpenBSD__
# include <err.h>
# endif
# endif
#endif
#include "lib/raop.h"
#include "lib/stream.h"
#include "lib/logger.h"
#include "lib/dnssd.h"
#include "lib/crypto.h"
#include "renderers/video_renderer.h"
#include "renderers/audio_renderer.h"
#include "renderers/mux_renderer.h"
#ifdef DBUS
#include <dbus/dbus.h>
#endif
#define VERSION "1.73"
#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 MISSED_FEEDBACK_LIMIT 15
#define MIN_PASSWORD_LENGTH 4
#define DEFAULT_PLAYBIN_VERSION 3
#define BT709_FIX "capssetter caps=\"video/x-h264, colorimetry=bt709\""
#define SRGB_FIX " ! video/x-raw,colorimetry=sRGB,format=RGB ! "
#ifdef FULL_RANGE_RGB_FIX
#define DEFAULT_SRGB_FIX true
#else
#define DEFAULT_SRGB_FIX false
#endif
static std::string server_name = DEFAULT_NAME;
static bool server_name_is_utf8 = false;
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;
#if __APPLE__
static bool new_window_closing_behavior = false;
#else
static bool new_window_closing_behavior = true;
#endif
static bool close_window;
static bool full_video_reset = true;
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 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 bool render_coverart = false;
static std::string coverart_filename = "";
static std::string metadata_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 bool suppress_packet_debug_data = false;
static int log_level = LOGGER_INFO;
static bool bt709_fix = false;
static bool srgb_fix = DEFAULT_SRGB_FIX;
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 unsigned char pin_pw = 0; /* 0: no client access control; 1: onscreen pin ; 2: require password (same password for all clients) 3: random pw*/
static std::string password = "";
static guint min_password_length = MIN_PASSWORD_LENGTH;
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 double initial_volume = 0.0;
static bool h265_support = false;
static int n_video_renderers = 0;
static int n_audio_renderers = 0;
static bool hls_support = false;
static std::string lang = "";
static std::string url = "";
static guint gst_x11_window_id = 0;
static guint video_eos_watch_id = 0;
static guint progress_id = 0;
static guint gst_hls_position_id = 0;
static bool preserve_connections = false;
static guint missed_feedback_limit = MISSED_FEEDBACK_LIMIT;
static guint missed_feedback = 0;
static guint playbin_version = DEFAULT_PLAYBIN_VERSION;
static bool reset_httpd = false;
static bool monitor_progress = false;
static uint32_t rtptime = 0;
static uint32_t rtptime_prev = 0;
static uint32_t rtptime_start = 0;
static uint32_t rtptime_end = 0;
static uint32_t rtptime_coverart_expired = 0;
static std::string artist;
static std::string track_title;
static std::string track_album;
static std::string coverart_artist;
static std::string ble_filename = "";
static std::string rtp_pipeline = "";
static std::string audio_rtp_pipeline = "";
static GMainLoop *gmainloop = NULL;
static bool mux_to_file = false;
static std::string mux_filename = "recording";
//Support for D-Bus-based screensaver inhibition (org.freedesktop.ScreenSaver)
static unsigned int scrsv = 0;
#ifdef DBUS
/* these strings can be changed at startup if a non-conforming Desktop Environmemt is detected */
static std::string dbus_service = "org.freedesktop.ScreenSaver";
static std::string dbus_path = "/org/freedesktop/ScreenSaver";
static std::string dbus_interface = "org.freedesktop.ScreenSaver";
static std::string dbus_inhibit = "Inhibit";
static std::string dbus_uninhibit = "UnInhibit";
static DBusConnection *dbus_connection = NULL;
static dbus_uint32_t dbus_cookie = 0;
static DBusPendingCall *dbus_pending = NULL;
static bool dbus_last_message = false;
static const char *appname = DEFAULT_NAME;
static const char *reason_always = "mirroring client: inhibit always";
static const char *reason_active = "actively receiving video";
static int activity_count;
static float previous_hls_position = 0.0f;
static double activity_threshold = 500000.0; // threshold for FPSdata item txUsageAvg to classify mirror video as "active"
#define MAX_ACTIVITY_COUNT 60
#endif
/* 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__)
#ifdef DBUS
static void dbus_screensaver_inhibiter(bool inhibit) {
g_assert(inhibit != dbus_last_message);
g_assert(scrsv);
/* receive reply from previous request, whenever that was sent
* (may have been sent hours ago ... !)
* (code modeled on vlc/modules/misc/inhibit/dbus.c) */
if (dbus_pending != NULL) {
DBusMessage *reply;
dbus_pending_call_block(dbus_pending);
reply = dbus_pending_call_steal_reply(dbus_pending);
dbus_pending_call_unref(dbus_pending);
dbus_pending = NULL;
if (reply != NULL) {
if (!dbus_message_get_args(reply, NULL,
DBUS_TYPE_UINT32, &dbus_cookie,
DBUS_TYPE_INVALID)) {
dbus_cookie = 0;
}
dbus_message_unref(reply);
}
LOGD("screen_saver: got D-Bus cookie %" PRIu32, (uint32_t) dbus_cookie);
}
if (!dbus_cookie && !inhibit) {
return; /* nothing to do */
}
/* send request */
const char *dbus_method = inhibit ? dbus_inhibit.c_str() : dbus_uninhibit.c_str();
DBusMessage *dbus_message = dbus_message_new_method_call(dbus_service.c_str(),
dbus_path.c_str(),
dbus_interface.c_str(),
dbus_method);
g_assert (dbus_message);
if (inhibit) {
dbus_bool_t ret;
const char *reason = (scrsv == 1) ? reason_active : reason_always;
ret = dbus_message_append_args(dbus_message,
DBUS_TYPE_STRING, &appname,
DBUS_TYPE_STRING, &reason,
DBUS_TYPE_INVALID);
g_assert(ret);
ret = dbus_connection_send_with_reply(dbus_connection, dbus_message, &dbus_pending, -1);
if (!ret) {
dbus_pending = NULL;
}
} else {
g_assert(dbus_cookie);
LOGD("screen_saver: releasing D-Bus cookie %" PRIu32, (uint32_t) dbus_cookie);
if (dbus_message_append_args(dbus_message,
DBUS_TYPE_UINT32, &dbus_cookie,
DBUS_TYPE_INVALID)
&& dbus_connection_send(dbus_connection, dbus_message, NULL)) {
dbus_cookie = 0;
}
}
dbus_connection_flush(dbus_connection);
dbus_message_unref(dbus_message);
dbus_last_message = inhibit;
}
#endif
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");
if (!fp) {
printf("Failed to open file %s\n", filename);
return 0;
}
size_t count = fwrite(image, 1, len, fp);
fclose(fp);
return count;
}
static size_t write_metadata(const char *filename, const char *text) {
FILE *fp = fopen(filename, "wb");
if (!fp) {
printf("Failed to open file %s\n", filename);
return 0;
}
size_t count = fwrite(text, sizeof(char), strlen(text) + 1, fp);
fclose(fp);
return count;
}
static int write_bledata( const uint32_t *pid, const char *process_name, const char *filename) {
char name[16] { 0 };
size_t len = strlen(process_name);
FILE *fp = fopen(filename, "wb");
if (!fp) {
printf("Failed to open file %s\n", filename);
return 0;
}
printf("port %u\n", raop_port);
size_t count = sizeof(uint16_t) * fwrite(&raop_port, sizeof(uint16_t), 1, fp);
count += sizeof(uint32_t) * fwrite(pid, sizeof(uint32_t), 1, fp);
count += sizeof(char) * len * fwrite(process_name, 1, len * sizeof(char), fp);
fclose(fp);
return (int) 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 feedback_callback(gpointer loop) {
if (open_connections) {
if (missed_feedback_limit && missed_feedback > missed_feedback_limit) {
LOGI("***ERROR lost connection with client (network problem?)");
LOGI(" Interval since last client feedback request exceeds limit of %u seconds", missed_feedback_limit);
LOGI(" Sometimes the network connection may recover after a longer delay:\n"
" the default limit n = %d seconds, can be changed with the \"-reset n\" option", MISSED_FEEDBACK_LIMIT);
if (!nofreeze) {
close_window = false; /* leave "frozen" window open if reset_video is false */
}
reset_httpd = true;
relaunch_video = true;
full_video_reset = true;
g_main_loop_quit((GMainLoop *) loop);
return TRUE;
} else if (missed_feedback > 2) {
LOGE("%3u seconds since last client feedback request (expected every two seconds); client may be offline", missed_feedback);
}
missed_feedback++;
} else {
missed_feedback = 0;
}
return TRUE;
}
static gboolean reset_callback(gpointer loop) {
if (reset_loop) {
g_main_loop_quit((GMainLoop *) loop);
}
return TRUE;
}
static gboolean x11_window_callback(gpointer loop) {
/* called while trying to find an x11 window used by playbin (HLS mode) */
if (waiting_for_x11_window()) {
return TRUE;
}
g_source_remove(gst_x11_window_id);
gst_x11_window_id = 0;
return FALSE;
}
/* signals handlers (ctrl-c, etc )*/
static void cleanup();
#ifdef _WIN32
static gboolean handle_signal(gpointer data) {
relaunch_video = false;
g_main_loop_quit(gmainloop);
return G_SOURCE_REMOVE;
}
static BOOL WINAPI CtrlHandler(DWORD signal) {
switch (signal) {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
if (gmainloop) {
g_idle_add(handle_signal, NULL);
return TRUE;
} else {
cleanup();
exit(0);
}
default:
return FALSE;
}
}
#else
static void CtrlHandler(int signum) {
cleanup();
exit(0);
}
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;
}
static gboolean sighup_callback(gpointer loop) {
relaunch_video = false;
g_main_loop_quit((GMainLoop *) loop);
return TRUE;
}
#endif
static void display_progress(uint32_t start, uint32_t curr, uint32_t end) {
if (curr < start || curr > end) {
return;
}
int duration = (int) (end - start)/44100;
int position = (int) (curr - start)/44100;
int remain = duration - position;
printf("audio progress (min:sec): %3d:%2.2d; remaining: %3d:%2.2d; track length %d:%2.2d\r",
position/60, position%60, remain/60, remain%60, duration/60, duration%60);
fflush(NULL);
}
static gboolean progress_callback (gpointer loop) {
if (monitor_progress) {
if ((rtptime_start || rtptime_end) && rtptime != rtptime_prev ) { //only display if rtptime has changed since last call
display_progress(rtptime_start, rtptime, rtptime_end);
rtptime_prev = rtptime;
}
if (render_coverart && coverart_artist == "_expired_" && rtptime - rtptime_coverart_expired > 44100 * 5) {
/* remove any expired coverart still being rendered more than 5 secs after it expired */
coverart_artist.erase();
video_renderer_cycle();
}
return TRUE;
} else {
progress_id = 0;
return FALSE;
}
}
static gboolean video_eos_watch_callback (gpointer loop) {
if (video_renderer_eos_watch()) {
/* HLS video has sent EOS */
LOGI("hls video has sent EOS");
video_renderer_hls_ready();
raop_handle_eos(raop);
}
return TRUE;
}
#define MAX_VIDEO_RENDERERS 3
#define MAX_AUDIO_RENDERERS 2
static void main_loop() {
guint gst_video_bus_watch_id[MAX_VIDEO_RENDERERS] = { 0 };
guint gst_audio_bus_watch_id[MAX_AUDIO_RENDERERS] = { 0 };
GMainLoop *loop = g_main_loop_new(NULL,FALSE);
relaunch_video = false;
monitor_progress = false;
reset_loop = false;
reset_httpd = false;
preserve_connections = false;
n_video_renderers = 0;
n_audio_renderers = 0;
if (use_video) {
n_video_renderers = 1;
relaunch_video = true;
if (url.empty()) {
if (h265_support) {
n_video_renderers++;
}
if (render_coverart) {
n_video_renderers++;
}
/* renderer[0] : h264 video; followed by h265 video (optional) and jpeg (optional) */
gst_x11_window_id = 0;
video_eos_watch_id = 0;
} else {
/* hls video will be rendered: renderer[0] : hls */
url.erase();
video_eos_watch_id = g_timeout_add(100, (GSourceFunc) video_eos_watch_callback, (gpointer) loop);
gst_x11_window_id = g_timeout_add(100, (GSourceFunc) x11_window_callback, (gpointer) loop);
}
g_assert(n_video_renderers <= MAX_VIDEO_RENDERERS);
for (int i = 0; i < n_video_renderers; i++) {
gst_video_bus_watch_id[i] = (guint) video_renderer_listen((void *)loop, i);
}
}
if (use_audio) {
rtptime_start = 0;
rtptime_end = 0;
monitor_progress = true;
artist.erase();
coverart_artist.erase();
progress_id = g_timeout_add_seconds(1,(GSourceFunc) progress_callback, (gpointer) loop);
n_audio_renderers = 2;
g_assert(n_audio_renderers <= MAX_AUDIO_RENDERERS);
for (int i = 0; i < n_audio_renderers; i++) {
gst_audio_bus_watch_id[i] = (guint) audio_renderer_listen((void *)loop, i);
}
}
missed_feedback = 0;
guint feedback_watch_id = g_timeout_add_seconds(1, (GSourceFunc) feedback_callback, (gpointer) loop);
guint reset_watch_id = g_timeout_add(100, (GSourceFunc) reset_callback, (gpointer) loop);
#ifdef _WIN32
gmainloop = loop;
#else
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGHUP, SIG_DFL);
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);
guint sighup_watch_id = g_unix_signal_add(SIGHUP, (GSourceFunc) sigint_callback, (gpointer) loop);
#endif
g_main_loop_run(loop);
#ifdef _WIN32
gmainloop = NULL;
#else
signal(SIGINT, CtrlHandler); //switch back to non-mainloop CtrlHandler
signal(SIGTERM, CtrlHandler);
signal(SIGHUP, CtrlHandler);
if (sigint_watch_id > 0) g_source_remove(sigint_watch_id);
if (sigterm_watch_id > 0) g_source_remove(sigterm_watch_id);
if (sighup_watch_id > 0) g_source_remove(sighup_watch_id);
#endif
for (int i = 0; i < n_video_renderers; i++) {
if (gst_video_bus_watch_id[i] > 0) g_source_remove(gst_video_bus_watch_id[i]);
}
for (int i = 0; i < n_audio_renderers; i++) {
if (gst_audio_bus_watch_id[i] > 0) g_source_remove(gst_audio_bus_watch_id[i]);
}
if (gst_x11_window_id > 0) g_source_remove(gst_x11_window_id);
if (reset_watch_id > 0) g_source_remove(reset_watch_id);
if (progress_id > 0) g_source_remove(progress_id);
if (video_eos_watch_id > 0) g_source_remove(video_eos_watch_id);
if (feedback_watch_id > 0) g_source_remove(feedback_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;
}
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[4];
unsigned char random[6];
get_random_bytes(random, sizeof(random));
/* mark MAC address as locally administered, i.e. random */
random[0] = random[0] & ~0x01;
random[0] = random[0] | 0x02;
snprintf(str,3,"%2.2x", random[0]);
std::string mac_address(str);
for (int i = 1; i < 6; i++) {
snprintf(str,4,":%2.2x", random[i]);
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 network name of the AirPlay server (UTF-8/ascii)\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("-mp4 [fn] Record (non-HLS)audio/video to mp4 file \"fn.[n].[format].mp4\"\n");
printf(" n=1,2,.. format = H264/5, ALAC/AAC. Default fn=\"recording\"\n");
printf("-hls [v] Support HTTP Live Streaming (HLS), Youtube app video only: \n");
printf(" v = 2 or 3 (default 3) optionally selects video player version\n");
printf("-lang xx HLS language preferences (\"fr:es:..\", overrides $LANGUAGE)\n");
printf("-lang (or -lang 0): play undubbed HLS version (overrides $LANGUAGE)\n");
printf("-scrsv n Screensaver override n: 0=off 1=on during activity 2=always on\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("-pw [pwd] Require use of password to control client access;\n");
printf(" (with no pwd, pin entry is required at *each* connection.)\n");
printf(" (option \"-pw\" after \"-pin\" overrides it, and vice versa)\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("-vol <v> Set initial audio-streaming volume: range [mute=0.0:1.0=full]\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 with X11, Wayland, VAAPI, D3D11/12, kms)\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, vaapih264dec, vtdec,etc.\n");
printf(" choices: avdec_h264,vaapih264dec,nvdec,nvh264dec,v4l2h264dec\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,kmssink,fbdevsink,osxvideosink,\n");
printf(" d3d11videosink,d3d12videosink, etc.\n");
printf("-vs 0 Streamed audio only, with no video display window\n");
printf("-vrtp pl Use rtph26[4,5]pay to send decoded video elsewhere: \"pl\"\n");
printf(" is the remaining pipeline, starting with rtph26*pay options:\n");
printf(" e.g. \"config-interval=1 ! udpsink host=127.0.0.1 port=5000\"\n");
printf(" Writes output to \"fn.N.mp4\"\n");
printf("-v4l2 Use Video4Linux2 for GPU hardware h264 decoding\n");
printf("-bt709 Sometimes needed for Raspberry Pi models using Video4Linux2 \n");
printf("-srgb Display \"Full range\" [0-255] color, not \"Limited Range\"[16-235]\n");
printf(" This is a workaround for a GStreamer problem, until it is fixed\n");
printf("-srgb no Disable srgb option (use when enabled by default: Linux, *BSD)\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("-artp pl Use rtpL16pay to send decoded audio elsewhere: \"pl\"\n");
printf(" is the remaining pipeline, starting with rtpL16pay options:\n");
printf(" e.g. \"pt=96 ! udpsink host=127.0.0.1 port=5002\"\n");
printf("-al x Audio latency in seconds (default 0.25) reported to client.\n");
printf("-ca [<fn>]In Audio (ALAC) mode, render cover-art [or write to file <fn>]\n");
printf("-md <fn> In Airplay Audio (ALAC) mode, write metadata text to file <fn>\n");
printf("-reset n Reset after n seconds of client silence (default n=%d, 0=never)\n", MISSED_FEEDBACK_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("-nc no Cancel the -nc option (DO close video window) \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");