/
source.py
2042 lines (1858 loc) · 88 KB
/
source.py
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
# coding=utf8
# This file is part of Xpra.
# Copyright (C) 2011 Serviware (Arthur Huillet, <ahuillet@serviware.com>)
# Copyright (C) 2010-2015 Antoine Martin <antoine@devloop.org.uk>
# Copyright (C) 2008 Nathaniel Smith <njs@pobox.com>
# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
import os
import time
from collections import deque
from threading import Event
from math import sqrt
from xpra.log import Logger
log = Logger("server")
elog = Logger("encoding")
soundlog = Logger("sound")
keylog = Logger("keyboard")
cursorlog = Logger("cursor")
metalog = Logger("metadata")
printlog = Logger("printing")
filelog = Logger("file")
timeoutlog = Logger("timeout")
proxylog = Logger("proxy")
avsynclog = Logger("av-sync")
mmaplog = Logger("mmap")
dbuslog = Logger("dbus")
from xpra.server import ClientException
from xpra.server.source_stats import GlobalPerformanceStatistics
from xpra.server.window.window_video_source import WindowVideoSource
from xpra.server.window.window_source import WindowSource
from xpra.server.window.batch_config import DamageBatchConfig
from xpra.simple_stats import add_list_stats, std_unit
from xpra.codecs.video_helper import getVideoHelper
from xpra.codecs.codec_constants import video_spec
from xpra.net import compression
from xpra.net.compression import compressed_wrapper, Compressed, Uncompressed
from xpra.make_thread import make_thread
from xpra.os_util import platform_name, Queue, get_machine_id, get_user_uuid
from xpra.server.background_worker import add_work_item
from xpra.util import csv, std, typedict, updict, get_screen_info, CLIENT_PING_TIMEOUT, WORKSPACE_UNSET, DEFAULT_METADATA_SUPPORTED
NOYIELD = os.environ.get("XPRA_YIELD") is None
MAX_CLIPBOARD_PER_SECOND = int(os.environ.get("XPRA_CLIPBOARD_LIMIT", "20"))
ADD_LOCAL_PRINTERS = os.environ.get("XPRA_ADD_LOCAL_PRINTERS", "0")=="1"
try:
GRACE_PERCENT = int(os.environ.get("XPRA_GRACE_PERCENT", "90"))
except:
GRACE_PERCENT = 90
AV_SYNC_DELTA = int(os.environ.get("XPRA_AV_SYNC_DELTA", "0"))
def make_window_metadata(window, propname, get_transient_for=None, get_window_id=None):
def raw():
return window.get_property(propname)
if propname in ("title", "icon-title", "command"):
v = raw()
if v is None:
return {propname: ""}
return {propname: v.encode("utf-8")}
elif propname in ("pid", "workspace", "bypass-compositor"):
v = raw()
assert v is not None, "%s is None!" % propname
if v<0 or (v==WORKSPACE_UNSET and propname=="workspace"):
#meaningless
return {}
return {propname : v}
elif propname == "size-hints":
hints = raw()
if not hints:
return {}
return {"size-constraints": hints}
elif propname == "strut":
strut = raw()
if not strut:
strut = {}
else:
strut = strut.todict()
return {"strut": strut}
elif propname == "class-instance":
c_i = raw()
if c_i is None:
return {}
return {"class-instance": [x.encode("utf-8") for x in c_i]}
elif propname == "client-machine":
client_machine = raw()
if client_machine is None:
import socket
client_machine = socket.gethostname()
if client_machine is None:
return {}
return {"client-machine": client_machine.encode("utf-8")}
elif propname == "transient-for":
wid = None
if get_transient_for:
wid = get_transient_for(window)
if wid:
return {"transient-for" : wid}
return {}
elif propname in ("window-type", "shape", "menu"):
#always send unchanged:
return {propname : raw()}
elif propname in ("iconic", "fullscreen", "maximized", "decorations", "above", "below", "shaded", "sticky", "skip-taskbar", "skip-pager", "modal", "focused"):
#always send these when requested
return {propname : bool(raw())}
elif propname in ("has-alpha", "override-redirect", "tray", "shadow"):
v = raw()
if v is False:
#save space: all these properties are assumed false if unspecified
return {}
return {propname : v}
elif propname in ("role", "opacity", "fullscreen-monitors"):
v = raw()
if v is None or v=="":
return {}
return {propname : v}
elif propname == "xid":
return {"xid" : hex(raw() or 0)}
elif propname == "group-leader":
gl = raw()
if not gl or not get_window_id:
return {}
xid, gdkwin = gl
p = {}
if xid:
p["group-leader-xid"] = xid
if gdkwin and get_window_id:
glwid = get_window_id(gdkwin)
if glwid:
p["group-leader-wid"] = glwid
return p
#the properties below are not actually exported to the client (yet?)
#it was just easier to handle them here
#(convert to a type that can be encoded for xpra info):
elif propname in ("state", "protocols"):
return {"state" : list(raw() or [])}
elif propname == "allowed-actions":
return {"allowed-actions" : list(raw())}
elif propname == "frame":
frame = raw()
if not frame:
return {}
return {"frame" : list(frame)}
raise Exception("unhandled property name: %s" % propname)
class WindowPropertyFilter(object):
def __init__(self, property_name, value):
self.property_name = property_name
self.value = value
def get_window_value(self, window):
return window.get_property(self.property_name)
def show(self, window):
try:
v = self.get_window_value(window)
log("%s.show(%s) %s(..)=%s", type(self).__name__, window, self.get_window_value, v)
except Exception:
log("%s.show(%s) %s(..) error:", type(self).__name__, window, self.get_window_value, exc_info=True)
v = None
e = self.evaluate(v)
return e
def evaluate(self, window_value):
raise NotImplementedError()
class WindowPropertyIn(WindowPropertyFilter):
def evaluate(self, window_value):
return window_value in self.value
class WindowPropertyNotIn(WindowPropertyIn):
def evaluate(self, window_value):
return not(WindowPropertyIn.evaluate(window_value))
class ServerSource(object):
"""
A ServerSource represents a client connection.
It mediates between the server class (which only knows about actual window objects and display server events)
and the client specific WindowSource instances (which only know about window ids
and manage window pixel compression).
It sends messages to the client via its 'protocol' instance (the network connection),
directly for a number of cases (cursor, sound, notifications, etc)
or on behalf of the window sources for pixel data.
Strategy: if we have 'ordinary_packets' to send, send those.
When we don't, then send packets from the 'packet_queue'. (compressed pixels or clipboard data)
See 'next_packet'.
The UI thread calls damage(), which goes into WindowSource and eventually (batching may be involved)
adds the damage pixels ready for processing to the encode_work_queue,
items are picked off by the separate 'encode' thread (see 'encode_loop')
and added to the damage_packet_queue.
"""
def __init__(self, protocol, disconnect_cb, idle_add, timeout_add, source_remove,
idle_timeout, idle_timeout_cb, idle_grace_timeout_cb,
socket_dir, unix_socket_paths, dbus_control,
get_transient_for, get_focus, get_cursor_data_cb,
get_window_id,
window_filters,
supports_mmap, av_sync,
core_encodings, encodings, default_encoding, scaling_control,
sound_properties,
sound_source_plugin,
supports_speaker, supports_microphone,
speaker_codecs, microphone_codecs,
default_quality, default_min_quality,
default_speed, default_min_speed):
log("ServerSource%s", (protocol, disconnect_cb, idle_add, timeout_add, source_remove,
idle_timeout, idle_timeout_cb, idle_grace_timeout_cb,
socket_dir, unix_socket_paths, dbus_control,
get_transient_for, get_focus,
get_window_id,
window_filters,
supports_mmap, av_sync,
core_encodings, encodings, default_encoding, scaling_control,
sound_properties,
sound_source_plugin,
supports_speaker, supports_microphone,
speaker_codecs, microphone_codecs,
default_quality, default_min_quality,
default_speed, default_min_speed))
self.close_event = Event()
self.ordinary_packets = []
self.protocol = protocol
self.disconnect = disconnect_cb
self.idle_add = idle_add
self.timeout_add = timeout_add
self.source_remove = source_remove
self.idle = False
self.idle_timeout = idle_timeout
self.idle_timeout_cb = idle_timeout_cb
self.idle_grace_timeout_cb = idle_grace_timeout_cb
self.idle_timer = None
self.idle_grace_timer = None
self.schedule_idle_grace_timeout()
self.schedule_idle_timeout()
self.socket_dir = socket_dir
self.unix_socket_paths = unix_socket_paths
self.dbus_control = dbus_control
self.dbus_server = None
#pass it to window source:
WindowSource.staticinit(idle_add, timeout_add, source_remove)
self.get_transient_for = get_transient_for
self.get_focus = get_focus
self.get_cursor_data_cb = get_cursor_data_cb
self.get_window_id = get_window_id
self.window_filters = window_filters
# mmap:
self.supports_mmap = supports_mmap
self.mmap = None
self.mmap_size = 0
self.mmap_client_token = None #the token we write that the client may check
# mouse echo:
self.mouse_echo = False
self.mouse_last_position = None
# sound:
self.sound_properties = sound_properties
self.sound_source_plugin = sound_source_plugin
self.supports_speaker = supports_speaker
self.speaker_codecs = speaker_codecs
self.supports_microphone = supports_microphone
self.microphone_codecs = microphone_codecs
self.sound_source_sequence = 0
self.sound_source = None
self.sound_sink = None
self.av_sync = av_sync
self.av_sync_delay = 0
self.av_sync_delay_total = 0
self.av_sync_delta = AV_SYNC_DELTA
self.server_core_encodings = core_encodings
self.server_encodings = encodings
self.default_encoding = default_encoding
self.scaling_control = scaling_control
self.default_quality = default_quality #default encoding quality for lossy encodings
self.default_min_quality = default_min_quality #default minimum encoding quality
self.default_speed = default_speed #encoding speed (only used by x264)
self.default_min_speed = default_min_speed #default minimum encoding speed
self.default_batch_config = DamageBatchConfig() #contains default values, some of which may be supplied by the client
self.global_batch_config = self.default_batch_config.clone() #global batch config
self.connection_time = time.time()
# the queues of damage requests we work through:
self.encode_work_queue = Queue() #holds functions to call to compress data (pixels, clipboard)
#items placed in this queue are picked off by the "encode" thread,
#the functions should add the packets they generate to the 'packet_queue'
self.packet_queue = deque() #holds actual packets ready for sending (already encoded)
#these packets are picked off by the "protocol" via 'next_packet()'
#format: packet, wid, pixels, start_send_cb, end_send_cb
#(only packet is required - the rest can be 0/None for clipboard packets)
#if we "proxy video", we will modify the video helper to add
#new encoders, so we must make a deep copy to preserve the original
#which may be used by other clients (other ServerSource instances)
self.video_helper = getVideoHelper().clone()
#these statistics are shared by all WindowSource instances:
self.statistics = GlobalPerformanceStatistics()
self.last_user_event = time.time()
self.last_ping_echoed_time = 0
self.clipboard_stats = deque(maxlen=MAX_CLIPBOARD_PER_SECOND)
self.init_vars()
# ready for processing:
protocol.set_packet_source(self.next_packet)
self.encode_thread = make_thread(self.encode_loop, "encode")
self.encode_thread.start()
#for managing the recalculate_delays work:
self.calculate_window_ids = set()
self.calculate_due = False
self.calculate_last_time = 0
#dbus:
if self.dbus_control:
try:
from xpra.server.dbus.dbus_source import DBUS_Source
self.dbus_server = DBUS_Source(self, os.environ.get("DISPLAY", "").lstrip(":"))
dbuslog("Source DBUS_Server=%s", self.dbus_server)
except Exception as e:
dbuslog.error("Error setting up the source's DBUS server:")
dbuslog.error(" %s", e)
def __str__(self):
return "%s(%s)" % (type(self).__name__, self.protocol)
def init_vars(self):
self.encoding = None #the default encoding for all windows
self.encodings = [] #all the encodings supported by the client
self.core_encodings = []
self.rgb_formats = ["RGB"]
self.encoding_options = typedict()
self.icons_encoding_options = typedict()
self.default_encoding_options = typedict()
self.window_sources = {} #WindowSource for each Window ID
self.suspended = False
self.uuid = ""
self.machine_id = ""
self.hostname = ""
self.username = ""
self.name = ""
self.argv = []
# client capabilities/options:
self.client_type = None
self.client_version = None
self.client_revision= None
self.client_platform = None
self.client_machine = None
self.client_processor = None
self.client_release = None
self.client_proxy = False
self.auto_refresh_delay = 0
self.send_cursors = False
self.send_bell = False
self.send_notifications = False
self.send_windows = True
self.pointer_grabs = False
self.randr_notify = False
self.named_cursors = False
self.window_initiate_moveresize = False
self.clipboard_enabled = False
self.clipboard_notifications = False
self.clipboard_set_enabled = False
self.share = False
self.desktop_size = None
self.desktop_size_unscaled = None
self.desktop_size_server = None
self.screen_sizes = []
self.desktops = 1
self.desktop_names = []
self.system_tray = False
self.notify_startup_complete = False
self.control_commands = []
self.metadata_supported = []
self.show_desktop_allowed = False
self.supports_transparency = False
self.file_transfer = False
self.file_size_limit = 10
self.printing = False
self.printers = {}
self.vrefresh = -1
self.double_click_time = -1
self.double_click_distance = -1, -1
#what we send back in hello packet:
self.ui_client = True
self.wants_aliases = True
self.wants_encodings = True
self.wants_versions = True
self.wants_features = True
self.wants_display = True
self.wants_sound = True
self.wants_events = False
#sound props:
self.pulseaudio_id = None
self.pulseaudio_server = None
self.sound_decoders = []
self.sound_encoders = []
self.keyboard_config = None
self.send_cursor_pending = False
self.last_cursor_sent = None
def is_closed(self):
return self.close_event.isSet()
def close(self):
log("%s.close()", self)
self.close_event.set()
for window_source in self.window_sources.values():
window_source.cleanup()
self.window_sources = {}
#it is now safe to add the end of queue marker:
#(all window sources will have stopped queuing data)
self.encode_work_queue.put(None)
#this should be a noop since we inherit an initialized helper:
self.video_helper.cleanup()
if self.mmap:
self.mmap.close()
self.mmap = None
self.mmap_size = 0
self.stop_sending_sound()
self.remove_printers()
ds = self.dbus_server
if ds:
ds.cleanup()
self.dbus_server = None
def recalculate_delays(self):
""" calls update_averages() on ServerSource.statistics (GlobalStatistics)
and WindowSource.statistics (WindowPerformanceStatistics) for each window id in calculate_window_ids,
"""
log("recalculate_delays()")
if self.is_closed():
return
self.statistics.update_averages()
wids = list(self.calculate_window_ids) #make a copy so we don't clobber new wids
focus = self.get_focus()
sources = self.window_sources.items()
maximized_wids = [wid for wid, source in sources if source is not None and source.maximized]
fullscreen_wids = [wid for wid, source in sources if source is not None and source.fullscreen]
for wid in wids:
#this is safe because we only add to this set from other threads:
self.calculate_window_ids.remove(wid)
ws = self.window_sources.get(wid)
if ws is None:
continue
try:
ws.statistics.update_averages()
ws.calculate_batch_delay(wid==focus,
len(fullscreen_wids)>0 and wid not in fullscreen_wids,
len(maximized_wids)>0 and wid not in maximized_wids)
ws.reconfigure()
except:
log.error("error on window %s", wid, exc_info=True)
if self.is_closed():
return
#allow other threads to run
#(ideally this would be a low priority thread)
time.sleep(0)
#calculate weighted average as new global default delay:
now = time.time()
wdimsum, wdelay, tsize, tcount = 0, 0, 0, 0
for ws in list(self.window_sources.values()):
if ws.batch_config.last_updated<=0:
continue
w, h = ws.window_dimensions
tsize += w*h
tcount += 1
time_w = 2.0+(now-ws.batch_config.last_updated) #add 2 seconds to even things out
weight = w*h*time_w
wdelay += ws.batch_config.delay*weight
wdimsum += weight
if wdimsum>0 and tcount>0:
#weighted delay:
avg_size = tsize/tcount
wdelay = wdelay / wdimsum
#store the delay as a normalized value per megapixel:
delay = wdelay * 1000000 / avg_size
self.global_batch_config.last_delays.append((now, delay))
self.global_batch_config.delay = delay
def may_recalculate(self, wid):
self.calculate_window_ids.add(wid)
if self.calculate_due:
#already due
return
self.calculate_due = True
def recalculate_work():
self.calculate_due = False
self.calculate_last_time = time.time()
self.recalculate_delays()
delta = time.time() - self.calculate_last_time
RECALCULATE_DELAY = 1.0 #1s
if delta>RECALCULATE_DELAY:
add_work_item(recalculate_work)
else:
self.timeout_add(int(1000*(RECALCULATE_DELAY-delta)), add_work_item, recalculate_work)
def suspend(self, ui, wd):
log("suspend(%s, %s) suspended=%s, sound_source=%s",
ui, wd, self.suspended, self.sound_source)
if ui:
self.suspended = True
for wid in wd.keys():
ws = self.window_sources.get(wid)
if ws:
ws.suspend()
def resume(self, ui, wd):
log("resume(%s, %s) suspended=%s, sound_source=%s",
ui, wd, self.suspended, self.sound_source)
if ui:
self.suspended = False
for wid, window in wd.items():
ws = self.window_sources.get(wid)
if ws:
ws.resume(window)
self.send_cursor()
def go_idle(self):
#usually fires from the server's idle_grace_timeout_cb
if self.idle:
return
self.idle = True
for window_source in self.window_sources.values():
window_source.go_idle()
def no_idle(self):
#on user event, we stop being idle
if not self.idle:
return
self.idle = False
for window_source in self.window_sources.values():
window_source.no_idle()
def user_event(self):
timeoutlog("user_event()")
self.last_user_event = time.time()
self.schedule_idle_grace_timeout()
self.schedule_idle_timeout()
if self.idle:
self.no_idle()
def schedule_idle_timeout(self):
timeoutlog("schedule_idle_timeout() idle_timer=%s, idle_timeout=%s", self.idle_timer, self.idle_timeout)
if self.idle_timer:
self.source_remove(self.idle_timer)
self.idle_timer = None
if self.idle_timeout>0:
self.idle_timer = self.timeout_add(self.idle_timeout*1000, self.idle_timedout)
def schedule_idle_grace_timeout(self):
timeoutlog("schedule_idle_grace_timeout() grace timer=%s, idle_timeout=%s", self.idle_grace_timer, self.idle_timeout)
if self.idle_grace_timer:
self.source_remove(self.idle_grace_timer)
self.idle_grace_timer = None
if self.idle_timeout>0 and not self.is_closed():
#grace timer is 90% of real timer:
grace = int(self.idle_timeout*1000*GRACE_PERCENT/100)
self.idle_grace_timer = self.timeout_add(grace, self.idle_grace_timedout)
def idle_grace_timedout(self):
self.idle_grace_timer = None
timeoutlog("idle_grace_timedout() callback=%s", self.idle_grace_timeout_cb)
self.idle_grace_timeout_cb(self)
def idle_timedout(self):
self.idle_timer = None
timeoutlog("idle_timedout() callback=%s", self.idle_timeout_cb)
self.idle_timeout_cb(self)
if not self.is_closed():
self.schedule_idle_timeout()
def parse_hello(self, c, min_mmap_size):
#batch options:
def batch_value(prop, default, minv=None, maxv=None):
assert default is not None
def parse_batch_int(value, varname):
if value is not None:
try:
return int(value)
except:
log.error("invalid value for batch option %s: %s", varname, value)
return None
#from client caps first:
cpname = "batch.%s" % prop
v = parse_batch_int(c.get(cpname), cpname)
#try env:
if v is None:
evname = "XPRA_BATCH_%s" % prop.upper()
v = parse_batch_int(os.environ.get(evname), evname)
#fallback to default:
if v is None:
v = default
if minv is not None:
v = max(minv, v)
if maxv is not None:
v = min(maxv, v)
assert v is not None
return v
self.ui_client = c.boolget("ui_client", True)
self.wants_encodings = c.boolget("wants_encodings", self.ui_client)
self.wants_display = c.boolget("wants_display", self.ui_client)
self.wants_sound = c.boolget("wants_sound", True)
self.wants_events = c.boolget("wants_events", False)
self.wants_aliases = c.boolget("wants_aliases", True)
self.wants_versions = c.boolget("wants_versions", True)
self.wants_features = c.boolget("wants_features", True)
self.default_batch_config.always = bool(batch_value("always", DamageBatchConfig.ALWAYS))
self.default_batch_config.min_delay = batch_value("min_delay", DamageBatchConfig.MIN_DELAY, 0, 1000)
self.default_batch_config.max_delay = batch_value("max_delay", DamageBatchConfig.MAX_DELAY, 1, 15000)
self.default_batch_config.max_events = batch_value("max_events", DamageBatchConfig.MAX_EVENTS)
self.default_batch_config.max_pixels = batch_value("max_pixels", DamageBatchConfig.MAX_PIXELS)
self.default_batch_config.time_unit = batch_value("time_unit", DamageBatchConfig.TIME_UNIT, 1)
self.default_batch_config.delay = batch_value("delay", DamageBatchConfig.START_DELAY, 0)
log("default batch config: %s", self.default_batch_config)
#client uuid:
self.uuid = c.strget("uuid")
self.machine_id = c.strget("machine_id")
self.hostname = c.strget("hostname")
self.username = c.strget("username")
self.name = c.strget("name")
self.argv = c.strlistget("argv")
self.client_type = c.strget("client_type", "PyGTK")
self.client_platform = c.strget("platform")
self.client_machine = c.strget("platform.machine")
self.client_processor = c.strget("platform.processor")
self.client_release = c.strget("platform.release")
self.client_version = c.strget("version")
self.client_revision = c.strget("build.revision")
self.client_proxy = c.boolget("proxy")
#general features:
self.zlib = c.boolget("zlib", True)
self.lz4 = c.boolget("lz4", False) and compression.use_lz4
self.lzo = c.boolget("lzo", False) and compression.use_lzo
self.send_windows = self.ui_client and c.boolget("windows", True)
self.pointer_grabs = c.boolget("pointer.grabs")
self.send_cursors = self.send_windows and c.boolget("cursors")
self.send_bell = c.boolget("bell")
self.send_notifications = c.boolget("notifications")
self.randr_notify = c.boolget("randr_notify")
self.mouse_echo = c.boolget("mouse.echo")
self.mouse_last_position = c.intpair("mouse.initial-position")
self.clipboard_enabled = c.boolget("clipboard", True)
self.clipboard_notifications = c.boolget("clipboard.notifications")
self.clipboard_set_enabled = c.boolget("clipboard.set_enabled")
self.share = c.boolget("share")
self.file_transfer = c.boolget("file-transfer")
self.file_size_limit = c.intget("file-size-limit")
self.printing = c.boolget("printing")
self.named_cursors = c.boolget("named_cursors")
self.window_initiate_moveresize = c.boolget("window.initiate-moveresize")
self.system_tray = c.boolget("system_tray")
self.control_commands = c.strlistget("control_commands")
self.metadata_supported = c.strlistget("metadata.supported", DEFAULT_METADATA_SUPPORTED)
self.show_desktop_allowed = c.boolget("show-desktop")
self.vrefresh = c.intget("vrefresh", -1)
self.double_click_time = c.intget("double_click.time")
self.double_click_distance = c.intpair("double_click.distance")
self.window_frame_sizes = typedict(c.dictget("window.frame_sizes") or {})
self.desktop_size = c.intpair("desktop_size")
if self.desktop_size is not None:
w, h = self.desktop_size
if w<=0 or h<=0 or w>=32768 or h>=32768:
log.warn("ignoring invalid desktop dimensions: %sx%s", w, h)
self.desktop_size = None
self.desktop_size_unscaled = c.intpair("desktop_size.unscaled")
self.set_screen_sizes(c.listget("screen_sizes"))
self.set_desktops(c.intget("desktops", 1), c.strlistget("desktop.names"))
#sound stuff:
self.pulseaudio_id = c.strget("sound.pulseaudio.id")
self.pulseaudio_server = c.strget("sound.pulseaudio.server")
self.sound_decoders = c.strlistget("sound.decoders", [])
self.sound_encoders = c.strlistget("sound.encoders", [])
self.sound_receive = c.boolget("sound.receive")
self.sound_send = c.boolget("sound.send")
av_sync = c.boolget("av-sync")
self.set_av_sync_delay(int(self.av_sync and av_sync) * c.intget("av-sync.delay.default", 150))
soundlog("pulseaudio id=%s, server=%s, sound decoders=%s, sound encoders=%s, receive=%s, send=%s",
self.pulseaudio_id, self.pulseaudio_server, self.sound_decoders, self.sound_encoders, self.sound_receive, self.sound_send)
avsynclog("av-sync: server=%s, client=%s, total=%s", self.av_sync, av_sync, self.av_sync_delay_total)
log("cursors=%s, bell=%s, notifications=%s", self.send_cursors, self.send_bell, self.send_notifications)
log("client uuid %s", self.uuid)
pinfo = ""
if self.client_platform:
pinfo = " %s" % platform_name(self.client_platform, c.strlistget("platform.linux_distribution") or self.client_release)
revinfo = ""
if self.client_revision:
revinfo="-r%s" % self.client_revision
log.info("%s%s client version %s%s", std(self.client_type), pinfo, std(self.client_version), std(revinfo))
msg = ""
if self.hostname:
msg += " connected from '%s'" % std(self.hostname)
if self.username:
msg += " as '%s'" % std(self.username)
if self.name and self.name!=self.username:
msg += " - '%s'" % std(self.name)
log.info(msg)
if c.boolget("proxy"):
proxy_hostname = c.strget("proxy.hostname")
proxy_platform = c.strget("proxy.platform")
proxy_release = c.strget("proxy.platform.release")
proxy_version = c.strget("proxy.version")
proxy_version = c.strget("proxy.build.version", proxy_version)
msg = "via %s proxy version %s" % (platform_name(proxy_platform, proxy_release), std(proxy_version))
if proxy_hostname:
msg += " on '%s'" % std(proxy_hostname)
proxylog.info(msg)
from xpra.version_util import version_compat_check
msg = version_compat_check(proxy_version)
if msg:
proxylog.warn("Warning: proxy version may not be compatible: %s", msg)
#keyboard is now injected into this class, default to undefined:
self.keyboard_config = None
#encodings:
self.encodings = c.strlistget("encodings")
self.core_encodings = c.strlistget("encodings.core", self.encodings)
self.rgb_formats = c.strlistget("encodings.rgb_formats", ["RGB"])
#skip all other encoding related settings if we don't send pixels:
if not self.send_windows:
log("windows/pixels forwarding is disabled for this client")
else:
self.parse_encoding_caps(c, min_mmap_size)
#window filters:
try:
for object_name, property_name, operator, value in c.listget("window-filters"):
self.add_window_filter(object_name, property_name, operator, value)
except Exception as e:
log.error("Error parsing window-filters: %s", e)
def parse_encoding_caps(self, c, min_mmap_size):
self.set_encoding(c.strget("encoding", None), None)
#encoding options (filter):
#1: these properties are special cased here because we
#defined their name before the "encoding." prefix convention,
#or because we want to pass default values (zlib/lz4):
for k,ek in {"initial_quality" : "initial_quality",
"quality" : "quality",
}.items():
if k in c:
self.encoding_options[ek] = c.intget(k)
for k,ek in {"zlib" : "rgb_zlib",
"lz4" : "rgb_lz4",
}.items():
if k in c:
self.encoding_options[ek] = c.boolget(k)
#2: standardized encoding options:
for k in c.keys():
if k.startswith("theme.") or k.startswith("encoding.icons."):
self.icons_encoding_options[k.replace("encoding.icons.", "").replace("theme.", "")] = c[k]
elif k.startswith("encoding."):
stripped_k = k[len("encoding."):]
if stripped_k in ("transparency",
"rgb_zlib", "rgb_lz4", "rgb_lzo",
"video_scaling"):
v = c.boolget(k)
elif stripped_k in ("initial_quality", "initial_speed",
"min-quality", "quality",
"min-speed", "speed"):
v = c.intget(k)
else:
v = c.get(k)
self.encoding_options[stripped_k] = v
elog("encoding options: %s", self.encoding_options)
elog("icons encoding options: %s", self.icons_encoding_options)
#handle proxy video: add proxy codec to video helper:
pv = self.encoding_options.boolget("proxy.video")
proxylog("proxy.video=%s", pv)
if pv:
#enabling video proxy:
try:
self.parse_proxy_video()
except:
proxylog.error("failed to parse proxy video", exc_info=True)
self.default_encoding_options["scaling.control"] = self.encoding_options.get("scaling.control", self.scaling_control)
q = self.encoding_options.intget("quality", self.default_quality) #0.7 onwards:
if q>0:
self.default_encoding_options["quality"] = q
mq = self.encoding_options.intget("min-quality", self.default_min_quality)
if mq>0 and (q<=0 or q>mq):
self.default_encoding_options["min-quality"] = mq
s = self.encoding_options.intget("speed", self.default_speed)
if s>0:
self.default_encoding_options["speed"] = s
ms = self.encoding_options.intget("min-speed", self.default_min_speed)
if ms>0 and (s<=0 or s>ms):
self.default_encoding_options["min-speed"] = ms
elog("default encoding options: %s", self.default_encoding_options)
self.auto_refresh_delay = c.intget("auto_refresh_delay", 0)
#mmap:
mmap_filename = c.strget("mmap_file")
mmap_token = c.intget("mmap_token")
mmaplog("client supplied mmap_file=%s, mmap supported=%s, token=%s", mmap_filename, self.supports_mmap, mmap_token)
if mmap_filename:
if not self.supports_mmap:
mmaplog("client supplied an mmap_file: %s but mmap mode is not supported", mmap_filename)
elif not os.path.exists(mmap_filename):
mmaplog("client supplied an mmap_file: %s but we cannot find it", mmap_filename)
else:
from xpra.net.mmap_pipe import init_server_mmap
from xpra.os_util import get_int_uuid
new_token = get_int_uuid()
self.mmap, self.mmap_size = init_server_mmap(mmap_filename, mmap_token, new_token)
mmaplog("found client mmap area: %s, %i bytes - min mmap size=%i", self.mmap, self.mmap_size, min_mmap_size)
if self.mmap_size>0:
if self.mmap_size<min_mmap_size:
mmaplog.warn("Warning: client supplied mmap area is too small, discarding it")
mmaplog.warn(" we need at least %i bytes and this area is %i", min_mmap_size, self.mmap_size)
self.mmap = None
self.mmap_size = 0
else:
self.mmap_client_token = new_token
if self.mmap_size>0:
mmaplog.info(" mmap is enabled using %sB area in %s", std_unit(self.mmap_size, unit=1024), mmap_filename)
else:
others = [x for x in self.core_encodings if x in self.server_core_encodings and x!=self.encoding]
elog.info(" using %s as primary encoding%s", self.encoding, [""," also available:"][int(len(others)>0)])
if others:
elog.info(" %s", ", ".join(others))
else:
elog.warn(" no other encodings are available!")
def parse_proxy_video(self):
from xpra.codecs.enc_proxy.encoder import Encoder
proxy_video_encodings = self.encoding_options.get("proxy.video.encodings")
proxylog("parse_proxy_video() proxy.video.encodings=%s", proxy_video_encodings)
for encoding, colorspace_specs in proxy_video_encodings.items():
for colorspace, spec_props in colorspace_specs.items():
for spec_prop in spec_props:
#make a new spec based on spec_props:
spec = video_spec(Encoder)
for k,v in spec_prop.items():
setattr(spec, k, v)
proxylog("parse_proxy_video() adding: %s / %s / %s", encoding, colorspace, spec)
self.video_helper.add_encoder_spec(encoding, colorspace, spec)
def startup_complete(self):
log("startup_complete()")
self.send("startup-complete")
def start_sending_sound(self, codec=None, volume=1.0):
soundlog("start_sending_sound(%s)", codec)
if self.suspended:
soundlog.warn("Warning: not starting sound whilst in suspended state")
return None
if not self.supports_speaker:
soundlog.error("Error sending sound: support not enabled on the server")
return None
if self.sound_source:
soundlog.error("Error sending sound: forwarding already in progress")
return None
if not self.sound_receive:
soundlog.error("Error sending sound: support is not enabled on the client")
return None
if codec is None:
from xpra.sound.gstreamer_util import CODEC_ORDER
codecs = [x for x in CODEC_ORDER if x in self.speaker_codecs and x in self.sound_decoders]
if not codecs:
soundlog.error("Error sending sound: no codecs in common")
return None
codec = codecs[0]
elif codec not in self.speaker_codecs:
soundlog.warn("Warning: invalid codec specified: %s", codec)
return None
elif codec not in self.sound_decoders:
soundlog.warn("Error sending sound: invalid codec '%s'", codec)
soundlog.warn(" is not in the list of decoders supported by the client: %s", csv(self.sound_decoders))
return None
ss = None
try:
from xpra.sound.gstreamer_util import ALLOW_SOUND_LOOP, loop_warning
if self.machine_id and self.machine_id==get_machine_id() and not ALLOW_SOUND_LOOP:
#looks like we're on the same machine, verify it's a different user:
if self.uuid==get_user_uuid():
loop_warning("speaker", self.uuid)
return None
from xpra.sound.wrapper import start_sending_sound
plugins = self.sound_properties.get("plugins")
ss = start_sending_sound(plugins, self.sound_source_plugin, codec, volume, [codec], self.pulseaudio_server, self.pulseaudio_id)
self.sound_source = ss
soundlog("start_sending_sound() sound source=%s", ss)
if not ss:
return None
ss.sequence = self.sound_source_sequence
ss.connect("new-buffer", self.new_sound_buffer)
ss.connect("new-stream", self.new_stream)
ss.connect("info", self.sound_source_info)
ss.connect("exit", self.sound_source_exit)
ss.start()
return ss
except Exception as e:
soundlog.error("error setting up sound: %s", e, exc_info=True)
self.stop_sending_sound()
ss = None
return None
finally:
if ss is None:
#tell the client we're not sending anything:
self.send_eos(codec)
def sound_source_exit(self, source, *args):
soundlog("sound_source_exit(%s, %s)", source, args)
if source==self.sound_source:
self.stop_sending_sound()
def sound_source_info(self, source, info):
soundlog("sound_source_info: %s", info)
def stop_sending_sound(self):
ss = self.sound_source
soundlog("stop_sending_sound() sound_source=%s", ss)
if ss:
self.sound_source = None
self.send_eos(ss.codec, ss.sequence)
ss.cleanup()
def send_eos(self, codec, sequence=0):
#tell the client this is the end:
self.send("sound-data", codec, "", {"end-of-stream" : True,
"sequence" : sequence})
def new_stream(self, sound_source, codec):
soundlog("new_stream(%s)", codec)
if self.sound_source!=sound_source:
soundlog("dropping new-stream signal (current source=%s, signal source=%s)", self.sound_source, sound_source)
return
sound_source.codec = codec
#tell the client this is the start:
self.send("sound-data", sound_source.codec, "",
{"start-of-stream" : True,
"codec" : sound_source.codec,
"sequence" : sound_source.sequence})
self.update_av_sync_delay_total()
def new_sound_buffer(self, sound_source, data, metadata):
soundlog("new_sound_buffer(%s, %s, %s) suspended=%s",
sound_source, len(data or []), metadata, self.suspended)
if self.sound_source!=sound_source or self.is_closed():
soundlog("sound buffer dropped: from old source or closed")
return
if sound_source.sequence<self.sound_source_sequence:
soundlog("sound buffer dropped: old sequence number: %s (current is %s)", sound_source.sequence, self.sound_source_sequence)
return
if sound_source.sequence>=0:
metadata["sequence"] = sound_source.sequence
self.send("sound-data", sound_source.codec, Compressed(sound_source.codec, data), metadata)
def stop_receiving_sound(self):
ss = self.sound_sink
soundlog("stop_receiving_sound() sound_sink=%s", ss)
if ss:
self.sound_sink = None
ss.cleanup()
def sound_control(self, action, *args):
soundlog("sound_control(%s, %s)", action, args)
if action=="stop":
if len(args)>0:
sequence = int(args[0])
if sequence!=self.sound_source_sequence:
log.warn("sound sequence mismatch: %i vs %i", sequence, self.sound_source_sequence)
return "not stopped"
soundlog("stop: sequence number matches")
self.stop_sending_sound()
return "stopped"
elif action in ("start", "fadein"):
codec = None