-
-
Notifications
You must be signed in to change notification settings - Fork 140
/
window_source.py
2578 lines (2374 loc) · 120 KB
/
window_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: utf-8 -*-
# This file is part of Xpra.
# Copyright (C) 2011 Serviware (Arthur Huillet, <ahuillet@serviware.com>)
# Copyright (C) 2010-2020 Antoine Martin <antoine@xpra.org>
# 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 hashlib
import threading
from math import sqrt
from collections import deque
from xpra.os_util import strtobytes, bytestostr, monotonic_time
from xpra.util import envint, envbool, csv, typedict, first_time
from xpra.common import MAX_WINDOW_SIZE
from xpra.server.window.windowicon_source import WindowIconSource
from xpra.server.window.window_stats import WindowPerformanceStatistics
from xpra.server.window.batch_config import DamageBatchConfig
from xpra.server.window.batch_delay_calculator import calculate_batch_delay, get_target_speed, get_target_quality
from xpra.server.cystats import time_weighted_average, logp #@UnresolvedImport
from xpra.rectangle import rectangle, add_rectangle, remove_rectangle, merge_all #@UnresolvedImport
from xpra.server.picture_encode import rgb_encode, webp_encode, mmap_send
from xpra.simple_stats import get_list_stats
from xpra.codecs.argb.argb import argb_swap #@UnresolvedImport
from xpra.codecs.rgb_transform import rgb_reformat
from xpra.codecs.loader import get_codec
from xpra.codecs.codec_constants import PREFERRED_ENCODING_ORDER, LOSSY_PIXEL_FORMATS
from xpra.net.compression import use, Compressed
from xpra.log import Logger
log = Logger("window", "encoding")
refreshlog = Logger("window", "refresh")
compresslog = Logger("window", "compress")
damagelog = Logger("window", "damage")
scalinglog = Logger("scaling")
iconlog = Logger("icon")
avsynclog = Logger("av-sync")
statslog = Logger("stats")
bandwidthlog = Logger("bandwidth")
AUTO_REFRESH = envbool("XPRA_AUTO_REFRESH", True)
AUTO_REFRESH_QUALITY = envint("XPRA_AUTO_REFRESH_QUALITY", 100)
AUTO_REFRESH_SPEED = envint("XPRA_AUTO_REFRESH_SPEED", 50)
INITIAL_QUALITY = envint("XPRA_INITIAL_QUALITY", 65)
INITIAL_SPEED = envint("XPRA_INITIAL_SPEED", 40)
LOCKED_BATCH_DELAY = envint("XPRA_LOCKED_BATCH_DELAY", 1000)
MAX_PIXELS_PREFER_RGB = envint("XPRA_MAX_PIXELS_PREFER_RGB", 4096)
MAX_RGB = envint("XPRA_MAX_RGB", 512*1024)
MIN_WINDOW_REGION_SIZE = envint("XPRA_MIN_WINDOW_REGION_SIZE", 1024)
MAX_SOFT_EXPIRED = envint("XPRA_MAX_SOFT_EXPIRED", 5)
ACK_JITTER = envint("XPRA_ACK_JITTER", 100)
ACK_TOLERANCE = envint("XPRA_ACK_TOLERANCE", 100)
SLOW_SEND_THRESHOLD = envint("XPRA_SLOW_SEND_THRESHOLD", 20*1000*1000)
HAS_ALPHA = envbool("XPRA_ALPHA", True)
FORCE_BATCH = envint("XPRA_FORCE_BATCH", True)
STRICT_MODE = envint("XPRA_ENCODING_STRICT_MODE", False)
MERGE_REGIONS = envbool("XPRA_MERGE_REGIONS", True)
DOWNSCALE_THRESHOLD = envint("XPRA_DOWNSCALE_THRESHOLD", 20)
INTEGRITY_HASH = envint("XPRA_INTEGRITY_HASH", False)
MAX_SYNC_BUFFER_SIZE = envint("XPRA_MAX_SYNC_BUFFER_SIZE", 256)*1024*1024 #256MB
AV_SYNC_RATE_CHANGE = envint("XPRA_AV_SYNC_RATE_CHANGE", 20)
AV_SYNC_TIME_CHANGE = envint("XPRA_AV_SYNC_TIME_CHANGE", 500)
SEND_TIMESTAMPS = envbool("XPRA_SEND_TIMESTAMPS", False)
DAMAGE_STATISTICS = envbool("XPRA_DAMAGE_STATISTICS", False)
SCROLL_ALL = envbool("XPRA_SCROLL_ALL", True)
HARDCODED_ENCODING = os.environ.get("XPRA_HARDCODED_ENCODING")
INFINITY = float("inf")
def get_env_encodings(etype, valid_options=()):
v = os.environ.get("XPRA_%s_ENCODINGS" % etype)
encodings = valid_options
if v:
options = v.split(",")
encodings = tuple(x for x in options if x in valid_options)
log("%s encodings: %s", etype, encodings)
return encodings
TRANSPARENCY_ENCODINGS = get_env_encodings("TRANSPARENCY", ("webp", "png", "rgb32"))
LOSSLESS_ENCODINGS = get_env_encodings("LOSSLESS", ("rgb", "png", "png/P", "png/L"))
REFRESH_ENCODINGS = get_env_encodings("REFRESH", ("webp", "png", "rgb24", "rgb32"))
LOSSLESS_WINDOW_TYPES = set(os.environ.get("XPRA_LOSSLESS_WINDOW_TYPES",
"DOCK,TOOLBAR,MENU,UTILITY,DROPDOWN_MENU,POPUP_MENU,TOOLTIP,NOTIFICATION,COMBO,DND").split(","))
class DelayedRegions:
def __init__(self, damage_time, regions, encoding, options):
self.expired = False
self.damage_time = damage_time
self.regions = regions
self.encoding = encoding
self.options = options or {}
def __repr__(self):
return "DelayedRegion(time=%i, expired=%s, encoding=%s, %i regions, options=%s)" % (
self.damage_time, self.expired, self.encoding, len(self.regions), self.options
)
def capr(v):
return min(100, max(0, int(v)))
class WindowSource(WindowIconSource):
"""
We create a Window Source for each window we send pixels for.
The UI thread calls 'damage' for screen updates,
we eventually call 'ClientConnection.call_in_encode_thread' to queue the damage compression,
the function can then submit the packet using the 'queue_damage_packet' callback.
(also by 'send_window_icon' and clibpoard packets)
"""
_encoding_warnings = set()
def __init__(self,
idle_add, timeout_add, source_remove,
ww, wh,
record_congestion_event, queue_size, call_in_encode_thread, queue_packet,
statistics,
wid, window, batch_config, auto_refresh_delay,
av_sync, av_sync_delay,
video_helper,
cuda_device_context,
server_core_encodings, server_encodings,
encoding, encodings, core_encodings, window_icon_encodings,
encoding_options, icons_encoding_options,
rgb_formats,
default_encoding_options,
mmap, mmap_size, bandwidth_limit, jitter):
super().__init__(window_icon_encodings, icons_encoding_options)
self.idle_add = idle_add
self.timeout_add = timeout_add
self.source_remove = source_remove
# mmap:
self._mmap = mmap
self._mmap_size = mmap_size
self.init_vars()
self.start_time = monotonic_time()
self.ui_thread = threading.current_thread()
self.record_congestion_event = record_congestion_event #callback for send latency problems
self.queue_size = queue_size #callback to get the size of the damage queue
self.call_in_encode_thread = call_in_encode_thread #callback to add damage data which is ready to compress to the damage processing queue
self.queue_packet = queue_packet #callback to add a network packet to the outgoing queue
self.wid = wid
self.window = window #only to be used from the UI thread!
self.global_statistics = statistics #shared/global statistics from ClientConnection
self.statistics = WindowPerformanceStatistics()
self.av_sync = av_sync #flag: enabled or not?
self.av_sync_delay = av_sync_delay #the av-sync delay we actually use
self.av_sync_delay_target = av_sync_delay #the av-sync delay we want at this point in time (can vary quickly)
self.av_sync_delay_base = av_sync_delay #the total av-sync delay we are trying to achieve (including video encoder delay)
self.av_sync_frame_delay = 0 #how long frames spend in the video encoder
self.av_sync_timer = None
self.encode_queue = []
self.encode_queue_max_size = 10
self.server_core_encodings = server_core_encodings
self.server_encodings = server_encodings
self.encoding = encoding #the current encoding
self.encodings = encodings #all the encodings supported by the client
self.core_encodings = core_encodings #the core encodings supported by the client
self.rgb_formats = rgb_formats #supported RGB formats (RGB, RGBA, ...) - used by mmap
self.encoding_options = encoding_options #extra options which may be specific to the encoder (ie: x264)
self.rgb_zlib = use("zlib") and encoding_options.boolget("rgb_zlib", True) #server and client support zlib pixel compression
self.rgb_lz4 = use("lz4") and encoding_options.boolget("rgb_lz4", False) #server and client support lz4 pixel compression
self.rgb_lzo = use("lzo") and encoding_options.boolget("rgb_lzo", False) #server and client support lzo pixel compression
self.client_render_size = encoding_options.get("render-size")
self.client_bit_depth = encoding_options.intget("bit-depth", 24)
self.supports_transparency = HAS_ALPHA and encoding_options.boolget("transparency")
self.full_frames_only = self.is_tray or encoding_options.boolget("full_frames_only")
self.client_refresh_encodings = encoding_options.strtupleget("auto_refresh_encodings")
self.max_soft_expired = max(0, min(100, encoding_options.intget("max-soft-expired", MAX_SOFT_EXPIRED)))
self.send_timetamps = encoding_options.boolget("send-timestamps", SEND_TIMESTAMPS)
self.send_window_size = encoding_options.boolget("send-window-size", False)
self.decoder_speed = typedict(self.encoding_options.dictget("decoder-speed") or {})
self.batch_config = batch_config
#auto-refresh:
self.auto_refresh_delay = auto_refresh_delay
self.base_auto_refresh_delay = auto_refresh_delay
self.last_auto_refresh_message = None
self.video_helper = video_helper
self.cuda_device_context = cuda_device_context
self.is_idle = False
self.is_OR = window.is_OR()
self.is_tray = window.is_tray()
self.is_shadow = window.is_shadow()
self.has_alpha = window.has_alpha()
self.window_dimensions = ww, wh
#where the window is mapped on the client:
self.mapped_at = None
self.fullscreen = not self.is_tray and window.get("fullscreen")
if default_encoding_options.get("scaling.control") is None:
self.scaling_control = None #means "auto"
else:
#ClientConnection sets defaults with the client's scaling.control value
self.scaling_control = default_encoding_options.intget("scaling.control", 1)
self.scaling = None
self.maximized = False #set by the client!
self.iconic = False
self.content_type = ""
self.window_signal_handlers = []
#watch for changes to properties that are used to derive the content-type:
if "content-type" in window.get_dynamic_property_names():
sid = window.connect("notify::content-type", self.content_type_changed)
self.window_signal_handlers.append(sid)
self.content_type_changed(window)
if "iconic" in window.get_dynamic_property_names():
self.iconic = window.get_property("iconic")
sid = window.connect("notify::iconic", self._iconic_changed)
self.window_signal_handlers.append(sid)
if "fullscreen" in window.get_dynamic_property_names():
sid = window.connect("notify::fullscreen", self._fullscreen_changed)
self.window_signal_handlers.append(sid)
if "children" in window.get_internal_property_names():
#we just copy the value to an attribute of window-source,
#so that we can access it from any thread
def children_updated(*_args):
self.children = window.get_property("children")
sid = window.connect("notify::children", children_updated)
self.window_signal_handlers.append(sid)
children_updated()
else:
self.children = None
#for deciding between small regions and full screen updates:
self.max_small_regions = 40
self.max_bytes_percent = 60
self.small_packet_cost = 1024
if mmap and mmap_size>0:
#with mmap, we can move lots of data around easily
#so favour large screen updates over small packets
self.max_small_regions = 10
self.max_bytes_percent = 25
self.small_packet_cost = 4096
self.bandwidth_limit = bandwidth_limit
self.jitter = jitter
self.pixel_format = None #ie: BGRX
self.image_depth = window.get_property("depth")
# general encoding tunables (mostly used by video encoders):
#keep track of the target encoding_quality: (event time, info, encoding speed):
self._encoding_quality = deque(maxlen=100)
self._encoding_quality_info = {}
#keep track of the target encoding_speed: (event time, info, encoding speed):
self._encoding_speed = deque(maxlen=100)
self._encoding_speed_info = {}
# they may have fixed values:
self._fixed_quality = default_encoding_options.get("quality", -1)
self._fixed_min_quality = capr(default_encoding_options.get("min-quality", 0))
self._fixed_speed = default_encoding_options.get("speed", -1)
self._fixed_min_speed = capr(default_encoding_options.get("min-speed", 0))
self._encoding_hint = None
self._quality_hint = self.window.get("quality", -1)
dyn_props = window.get_dynamic_property_names()
if "quality" in dyn_props:
sid = window.connect("notify::quality", self.quality_changed)
self.window_signal_handlers.append(sid)
self._speed_hint = self.window.get("speed", -1)
if "speed" in dyn_props:
sid = window.connect("notify::speed", self.speed_changed)
self.window_signal_handlers.append(sid)
if "encoding" in dyn_props:
sid = window.connect("notify::encoding", self.encoding_changed)
self.window_signal_handlers.append(sid)
self.window_type = set()
if "window-type" in dyn_props:
self.window_type = set(self.window.get_property("window-type"))
sid = window.connect("notify::window-type", self.window_type_changed)
self.window_signal_handlers.append(sid)
#will be overriden by update_quality() and update_speed() called from update_encoding_selection()
#just here for clarity:
nobwl = (self.bandwidth_limit or 0)<=0
if self._quality_hint>=0:
self._current_quality = capr(self._quality_hint)
elif self._fixed_quality>=0:
self._current_quality = capr(self._fixed_quality)
else:
self._current_quality = capr(encoding_options.intget("initial_quality", INITIAL_QUALITY*(1+int(nobwl))))
if self._speed_hint>=0:
self._current_speed = capr(self._speed_hint)
elif self._fixed_speed>=0:
self._current_speed = capr(self._fixed_speed)
else:
self._current_speed = capr(encoding_options.intget("initial_speed", INITIAL_SPEED*(1+int(nobwl))))
self._want_alpha = False
self._lossless_threshold_base = 85
self._lossless_threshold_pixel_boost = 20
self._rgb_auto_threshold = MAX_PIXELS_PREFER_RGB
self.init_encoders()
self.update_encoding_selection(encoding, init=True)
log("initial encoding for %s: %s", self.wid, self.encoding)
#ready to service:
self._damage_cancelled = 0
def __repr__(self):
return "WindowSource(%s : %s)" % (self.wid, self.window_dimensions)
def add_encoder(self, encoding, encoder):
log("add_encoder(%s, %s)", encoding, encoder)
self._all_encoders.setdefault(encoding, []).insert(0, encoder)
self._encoders[encoding] = encoder
def init_encoders(self):
self._all_encoders = {}
self._encoders = {}
self.full_csc_modes = typedict()
self.add_encoder("rgb24", self.rgb_encode)
self.add_encoder("rgb32", self.rgb_encode)
#we need pillow for scaling and grayscale:
self.enc_pillow = get_codec("enc_pillow")
if self._mmap_size>0:
self.add_encoder("mmap", self.mmap_encode)
return
if self.enc_pillow:
for x in self.enc_pillow.get_encodings():
if x in self.server_core_encodings:
self.add_encoder(x, self.pillow_encode)
#prefer these native encoders over the Pillow version:
if "webp" in self.server_core_encodings:
self.add_encoder("webp", self.webp_encode)
self.enc_jpeg = get_codec("enc_jpeg")
if "jpeg" in self.server_core_encodings and self.enc_jpeg:
self.add_encoder("jpeg", self.jpeg_encode)
#prefer nvjpeg over all the other jpeg encoders:
self.enc_nvjpeg = None
log("init_encoders() cuda_device_context=%s", self.cuda_device_context)
if self.cuda_device_context:
self.enc_nvjpeg = get_codec("enc_nvjpeg")
if self.enc_nvjpeg:
self.add_encoder("jpeg", self.nvjpeg_encode)
self.parse_csc_modes(self.encoding_options.dictget("full_csc_modes", default_value=None))
def init_vars(self):
self.server_core_encodings = ()
self.server_encodings = ()
self.encoding = None
self.encodings = ()
self.encoding_last_used = None
self.auto_refresh_encodings = ()
self.core_encodings = ()
self.rgb_formats = ()
self.full_csc_modes = typedict()
self.client_refresh_encodings = ()
self.encoding_options = {}
self.rgb_zlib = False
self.rgb_lz4 = False
self.rgb_lzo = False
self.supports_transparency = False
self.full_frames_only = False
self.suspended = False
self.strict = STRICT_MODE
self.decoder_speed = typedict()
#
self.decode_error_refresh_timer = None
self.may_send_timer = None
self.auto_refresh_delay = 0
self.base_auto_refresh_delay = 0
self.min_auto_refresh_delay = 50
self.video_helper = None
self.refresh_quality = AUTO_REFRESH_QUALITY
self.refresh_speed = AUTO_REFRESH_SPEED
self.refresh_event_time = 0
self.refresh_target_time = 0
self.refresh_timer = None
self.refresh_regions = []
self.timeout_timer = None
self.expire_timer = None
self.soft_timer = None
self.soft_expired = 0
self.max_soft_expired = MAX_SOFT_EXPIRED
self.is_OR = False
self.is_tray = False
self.is_shadow = False
self.has_alpha = False
self.window_dimensions = 0, 0
self.fullscreen = False
self.scaling_control = None
self.scaling = None
self.maximized = False
#
self.bandwidth_limit = 0
self.max_small_regions = 0
self.max_bytes_percent = 0
self.small_packet_cost = 0
#
self._encoding_quality = []
self._encoding_quality_info = {}
self._encoding_speed = []
self._encoding_speed_info = {}
#
self._fixed_quality = -1
self._fixed_min_quality = 0
self._fixed_speed = -1
self._fixed_min_speed = 0
#
self._damage_delayed = None
self._sequence = 1
self._damage_cancelled = INFINITY
self._damage_packet_sequence = 1
def cleanup(self):
self.cancel_damage(INFINITY)
log("encoding_totals for wid=%s with primary encoding=%s : %s",
self.wid, self.encoding, self.statistics.encoding_totals)
self.init_vars()
self._mmap_size = 0
self.batch_config.cleanup()
#we can only clear the encoders after clearing the whole encoding queue:
#(because mmap cannot be cancelled once queued for encoding)
self.call_in_encode_thread(False, self.encode_ended)
def encode_ended(self):
log("encode_ended()")
self._encoders = {}
self.idle_add(self.ui_cleanup)
def ui_cleanup(self):
log("ui_cleanup: will disconnect %s", self.window_signal_handlers)
for sid in self.window_signal_handlers:
self.window.disconnect(sid)
self.window_signal_handlers = []
self.window = None
self.batch_config = None
self.get_best_encoding = None
self.statistics = None
self.global_statistics = None
def get_info(self) -> dict:
#should get prefixed with "client[M].window[N]." by caller
"""
Add window specific stats
"""
info = self.statistics.get_info()
info.update(WindowIconSource.get_info(self))
einfo = info.setdefault("encoding", {}) #defined in statistics.get_info()
einfo.update(self.get_quality_speed_info())
einfo.update({
"" : self.encoding,
"lossless_threshold" : {
"base" : self._lossless_threshold_base,
"pixel_boost" : self._lossless_threshold_pixel_boost
},
})
try:
#ie: get_strict_encoding -> "strict_encoding"
einfo["selection"] = self.get_best_encoding.__name__.replace("get_", "")
except AttributeError:
pass
#"encodings" info:
esinfo = {
"" : self.encodings,
"core" : self.core_encodings,
"auto-refresh" : self.client_refresh_encodings,
"csc_modes" : self.full_csc_modes or {},
"decoder-speed" : dict(self.decoder_speed),
}
larm = self.last_auto_refresh_message
if larm:
esinfo.update({"auto-refresh" : {
"quality" : self.refresh_quality,
"speed" : self.refresh_speed,
"min-delay" : self.min_auto_refresh_delay,
"delay" : self.auto_refresh_delay,
"base-delay" : self.base_auto_refresh_delay,
"last-event" : {
"elapsed" : int(1000*(monotonic_time()-larm[0])),
"message" : larm[1],
}
}
})
#remove large default dict:
info.update({
"idle" : self.is_idle,
"dimensions" : self.window_dimensions,
"suspended" : self.suspended or False,
"bandwidth-limit" : self.bandwidth_limit,
"av-sync" : {
"enabled" : self.av_sync,
"current" : self.av_sync_delay,
"target" : self.av_sync_delay_target
},
"encodings" : esinfo,
"rgb_threshold" : self._rgb_auto_threshold,
"mmap" : self._mmap_size>0,
"last_used" : self.encoding_last_used or "",
"full-frames-only" : self.full_frames_only,
"supports-transparency" : self.supports_transparency,
"property" : self.get_property_info(),
"content-type" : self.content_type or "",
"batch" : self.batch_config.get_info(),
"soft-timeout" : {
"expired" : self.soft_expired,
"max" : self.max_soft_expired,
},
"send-timetamps" : self.send_timetamps,
"send-window-size" : self.send_window_size,
"rgb_formats" : self.rgb_formats,
"bit-depth" : {
"source" : self.image_depth,
"client" : self.client_bit_depth,
},
})
ma = self.mapped_at
if ma:
info["mapped-at"] = ma
crs = self.client_render_size
if crs:
info["render-size"] = crs
info["damage.fps"] = int(self.get_damage_fps())
if self.pixel_format:
info["pixel-format"] = self.pixel_format
cdd = self.cuda_device_context
if cdd:
info["cuda-device"] = cdd.get_info()
return info
def get_damage_fps(self):
now = monotonic_time()
cutoff = now-5
lde = tuple(x[0] for x in tuple(self.statistics.last_damage_events) if x[0]>=cutoff)
fps = 0
if len(lde)>=2:
elapsed = now-min(lde)
if elapsed>0:
fps = len(lde) // elapsed
return fps
def get_quality_speed_info(self) -> dict:
info = {}
def add_list_info(prefix, v, vinfo):
if not v:
return
l = tuple(v)
if not l:
li = {}
else:
li = get_list_stats(x for _, x in l)
li.update(vinfo)
info[prefix] = li
add_list_info("quality", self._encoding_quality, self._encoding_quality_info)
add_list_info("speed", self._encoding_speed, self._encoding_speed_info)
return info
def get_property_info(self) -> dict:
return {
"fullscreen" : self.fullscreen or False,
#speed / quality properties (not necessarily the same as the video encoder settings..):
"encoding-hint" : self._encoding_hint or "",
"min_speed" : self._fixed_min_speed,
"speed" : self._fixed_speed,
"speed-hint" : self._speed_hint,
"min_quality" : self._fixed_min_quality,
"quality" : self._fixed_quality,
"quality-hint" : self._quality_hint,
}
def go_idle(self):
self.is_idle = True
self.lock_batch_delay(LOCKED_BATCH_DELAY)
def no_idle(self):
self.is_idle = False
self.unlock_batch_delay()
def lock_batch_delay(self, delay):
""" use a fixed delay until unlock_batch_delay is called """
if not self.batch_config.locked:
self.batch_config.locked = True
self.batch_config.saved = self.batch_config.delay
self.batch_config.delay = max(delay, self.batch_config.delay)
def unlock_batch_delay(self):
if self.iconic or not self.batch_config.locked:
return
self.batch_config.locked = False
self.batch_config.delay = self.batch_config.saved
def suspend(self):
self.cancel_damage()
self.statistics.reset()
self.suspended = True
def resume(self):
assert self.ui_thread == threading.current_thread()
self.cancel_damage()
self.statistics.reset()
self.suspended = False
self.refresh({"quality" : 100})
if not self.is_OR and not self.is_tray and "icons" in self.window.get_property_names():
self.send_window_icon()
def refresh(self, options=None):
assert self.ui_thread == threading.current_thread()
w, h = self.window.get_dimensions()
self.damage(0, 0, w, h, options)
def set_scaling(self, scaling):
scalinglog("set_scaling(%s)", scaling)
self.scaling = scaling
self.reconfigure(True)
def set_scaling_control(self, scaling_control):
scalinglog("set_scaling_control(%s)", scaling_control)
if scaling_control is None:
self.scaling_control = None
else:
self.scaling_control = max(0, min(100, scaling_control))
self.reconfigure(True)
def _fullscreen_changed(self, _window, *_args):
self.fullscreen = self.window.get_property("fullscreen")
log("window fullscreen state changed: %s", self.fullscreen)
self.reconfigure(True)
def _iconic_changed(self, _window, *_args):
self.iconic = self.window.get_property("iconic")
if self.iconic:
self.go_idle()
else:
self.no_idle()
def content_type_changed(self, window, *args):
self.content_type = window.get("content-type")
log("content_type_changed(%s, %s) content-type=%s", window, args, self.content_type)
return True
def quality_changed(self, window, *args):
self._quality_hint = window.get("quality", -1)
log("quality_changed(%s, %s) quality=%s", window, args, self._quality_hint)
return True
def speed_changed(self, window, *args):
self._speed_hint = window.get("speed", -1)
log("speed_changed(%s, %s) speed=%s", window, args, self._speed_hint)
return True
def encoding_changed(self, window, *args):
v = window.get("encoding", None)
if v and v not in self._encoders:
log.warn("Warning: invalid encoding hint '%s'", v)
log.warn(" this encoding is not supported")
v = None
self._encoding_hint = v
self.assign_encoding_getter()
log("encoding_changed(%s, %s) encoding-hint=%s, selection=%s",
window, args, self._encoding_hint, self.get_best_encoding)
return True
def window_type_changed(self, window, *args):
self.window_type = set(window.get_property("window-type"))
log("window_type_changed(window, %s) window_type=%s", window, args, self.window_type)
self.assign_encoding_getter()
def set_client_properties(self, properties):
#filter out stuff we don't care about
#to see if there is anything to set at all,
#and if not, don't bother doing the potentially expensive update_encoding_selection()
for k in ("workspace", "screen"):
if k in properties:
del properties[k]
elif strtobytes(k) in properties:
del properties[strtobytes(k)]
if properties:
self.do_set_client_properties(properties)
def do_set_client_properties(self, properties):
self.maximized = properties.boolget("maximized", False)
self.client_render_size = properties.intpair("encoding.render-size")
self.client_bit_depth = properties.intget("bit-depth", self.client_bit_depth)
self.client_refresh_encodings = properties.strtupleget("encoding.auto_refresh_encodings", self.client_refresh_encodings)
self.full_frames_only = self.is_tray or properties.boolget("encoding.full_frames_only", self.full_frames_only)
self.supports_transparency = HAS_ALPHA and properties.boolget("encoding.transparency", self.supports_transparency)
self.encodings = properties.strtupleget("encodings", self.encodings)
self.core_encodings = properties.strtupleget("encodings.core", self.core_encodings)
self.decoder_speed = typedict(properties.dictget("decoder-speed", self.decoder_speed))
rgb_formats = properties.strtupleget("encodings.rgb_formats", self.rgb_formats)
if not self.supports_transparency:
#remove rgb formats with alpha
rgb_formats = [x for x in rgb_formats if x.find("A")<0]
self.rgb_formats = rgb_formats
self.send_window_size = properties.boolget("encoding.send-window-size", self.send_window_size)
self.parse_csc_modes(properties.dictget("encoding.full_csc_modes", default_value=None))
#select the defaults encoders:
#(in case pillow was selected previously and the client side scaling changed)
for encoding, encoders in self._all_encoders.items():
self._encoders[encoding] = encoders[0]
#we may now want to downscale server-side,
#or convert to grayscale,
#and for that we need to use the pillow encoder:
grayscale = self.encoding=="grayscale"
if self.enc_pillow and (self.client_render_size or grayscale):
crsw, crsh = self.client_render_size
ww, wh = self.window_dimensions
if grayscale or (ww-crsw>DOWNSCALE_THRESHOLD and wh-crsh>DOWNSCALE_THRESHOLD):
for x in self.enc_pillow.get_encodings():
if x in self.server_core_encodings:
self.add_encoder(x, self.pillow_encode)
self.update_encoding_selection(self.encoding)
def parse_csc_modes(self, full_csc_modes):
#only override if values are specified:
log("parse_csc_modes(%s) current value=%s", full_csc_modes, self.full_csc_modes)
if full_csc_modes is not None and isinstance(full_csc_modes, dict):
self.full_csc_modes = typedict(full_csc_modes)
def set_auto_refresh_delay(self, d):
self.auto_refresh_delay = d
self.update_refresh_attributes()
def set_av_sync_delay(self, new_delay):
self.av_sync_delay_base = new_delay
self.may_update_av_sync_delay()
def may_update_av_sync_delay(self):
#set the target then schedule a timer to gradually
#get the actual value "av_sync_delay" moved towards it
self.av_sync_delay_target = max(0, self.av_sync_delay_base - self.av_sync_frame_delay)
avsynclog("may_update_av_sync_delay() target=%s from base=%s, frame-delay=%s",
self.av_sync_delay_target, self.av_sync_delay_base, self.av_sync_frame_delay)
self.schedule_av_sync_update()
def schedule_av_sync_update(self, delay=0):
avsynclog("schedule_av_sync_update(%i) wid=%i, delay=%i, target=%i, timer=%s",
delay, self.wid, self.av_sync_delay, self.av_sync_delay_target, self.av_sync_timer)
if not self.av_sync:
self.av_sync_delay = 0
return
if self.av_sync_delay==self.av_sync_delay_target:
return #already up to date
if self.av_sync_timer:
return #already scheduled
self.av_sync_timer = self.timeout_add(delay, self.update_av_sync_delay)
def update_av_sync_delay(self):
self.av_sync_timer = None
delta = self.av_sync_delay_target-self.av_sync_delay
if delta==0:
return
#limit the rate of change:
rdelta = min(AV_SYNC_RATE_CHANGE, max(-AV_SYNC_RATE_CHANGE, delta))
avsynclog("update_av_sync_delay() wid=%i, current=%s, target=%s, adding %s (capped to +-%s from %s)",
self.wid, self.av_sync_delay, self.av_sync_delay_target, rdelta, AV_SYNC_RATE_CHANGE, delta)
self.av_sync_delay += rdelta
if self.av_sync_delay!=self.av_sync_delay_target:
self.schedule_av_sync_update(AV_SYNC_TIME_CHANGE)
def set_new_encoding(self, encoding, strict):
if strict is not None or STRICT_MODE:
self.strict = strict or STRICT_MODE
if self.encoding==encoding:
return
self.statistics.reset()
self.update_encoding_selection(encoding)
def update_encoding_selection(self, encoding=None, exclude=(), init=False):
#now we have the real list of encodings we can use:
#"rgb32" and "rgb24" encodings are both aliased to "rgb"
if self._mmap_size>0 and self.encoding!="grayscale":
self.auto_refresh_encodings = ()
self.encoding = "mmap"
self.encodings = ("mmap", )
self.common_encodings = ("mmap", )
self.get_best_encoding = self.encoding_is_mmap
return
common_encodings = [x for x in self._encoders if x in self.core_encodings and x not in exclude]
#"rgb" is a pseudo encoding and needs special code:
if "rgb24" in common_encodings or "rgb32" in common_encodings:
common_encodings.append("rgb")
self.common_encodings = tuple(x for x in PREFERRED_ENCODING_ORDER if x in common_encodings)
if not self.common_encodings:
raise Exception("no common encodings found (server: %s vs client: %s, excluding: %s)" % (csv(self._encoders.keys()), csv(self.core_encodings), csv(exclude)))
#ensure the encoding chosen is supported by this source:
if (encoding in self.common_encodings or encoding in ("auto", "grayscale")) and len(self.common_encodings)>1:
self.encoding = encoding
else:
self.encoding = self.common_encodings[0]
log("ws.update_encoding_selection(%s, %s, %s) encoding=%s, common encodings=%s",
encoding, exclude, init, self.encoding, self.common_encodings)
assert self.encoding is not None
#auto-refresh:
if self.client_refresh_encodings:
#client supplied list, honour it:
ropts = set(self.client_refresh_encodings)
else:
#sane defaults:
ropts = set(REFRESH_ENCODINGS) #default encodings for auto-refresh
if self.refresh_quality<100 and self.image_depth>16:
ropts.add("jpeg")
are = ()
if self.supports_transparency:
are = tuple(x for x in self.common_encodings if x in ropts and x in TRANSPARENCY_ENCODINGS)
if not are:
are = tuple(x for x in self.common_encodings if x in ropts) or self.common_encodings
self.auto_refresh_encodings = tuple(x for x in PREFERRED_ENCODING_ORDER if x in are)
log("update_encoding_selection: client refresh encodings=%s, auto_refresh_encodings=%s",
self.client_refresh_encodings, self.auto_refresh_encodings)
self.update_quality()
self.update_speed()
self.update_encoding_options()
self.update_refresh_attributes()
def _more_lossless(self):
return False
def update_encoding_options(self, force_reload=False):
self._want_alpha = self.is_tray or (self.has_alpha and self.supports_transparency)
ml = self._more_lossless()
self._lossless_threshold_base = min(90-10*ml, 60-ml*20+self._current_speed//5)
if self.content_type=="text" or self.is_shadow:
self._lossless_threshold_base -= 20
self._lossless_threshold_pixel_boost = max(5, 20-self._current_speed//5)
#calculate the threshold for using rgb
#if speed is high, assume we have bandwidth to spare
smult = max(0.25, (self._current_speed-50)/5.0)
qmult = max(0, self._current_quality/20.0)
pcmult = min(20, 0.5+self.statistics.packet_count)/20.0
max_rgb_threshold = 32*1024
min_rgb_threshold = 2048
cv = self.global_statistics.congestion_value
if cv>0.1:
max_rgb_threshold = int(32*1024/(1+cv))
min_rgb_threshold = 1024
bwl = self.bandwidth_limit
if bwl:
max_rgb_threshold = min(max_rgb_threshold, max(bwl//1000, 1024))
v = int(MAX_PIXELS_PREFER_RGB * pcmult * smult * qmult * (1 + int(self.is_OR or self.is_tray or self.is_shadow)*2))
crs = self.client_render_size
if crs:
ww, wh = self.window_dimensions
if crs[0]<ww or crs[1]<wh:
#client will downscale, best to avoid sending rgb,
#so we can more easily downscale at this end:
max_rgb_threshold = 1024
self._rgb_auto_threshold = min(max_rgb_threshold, max(min_rgb_threshold, v))
self.assign_encoding_getter()
log("update_encoding_options(%s) wid=%i, want_alpha=%s, speed=%i, quality=%i, bandwidth-limit=%i, lossless threshold: %s / %s, rgb auto threshold=%i (min=%i, max=%i), get_best_encoding=%s",
force_reload, self.wid, self._want_alpha, self._current_speed, self._current_quality, bwl, self._lossless_threshold_base, self._lossless_threshold_pixel_boost, self._rgb_auto_threshold, min_rgb_threshold, max_rgb_threshold, self.get_best_encoding)
def assign_encoding_getter(self):
self.get_best_encoding = self.get_best_encoding_impl()
def get_best_encoding_impl(self):
if HARDCODED_ENCODING:
return self.hardcoded_encoding
if self._encoding_hint and self._encoding_hint in self._encoders:
return self.encoding_is_hint
#choose which method to use for selecting an encoding
#first the easy ones (when there is no choice):
if self._mmap_size>0 and self.encoding!="grayscale":
return self.encoding_is_mmap
elif self.encoding=="png/L":
#(png/L would look awful if we mixed it with something else)
return self.encoding_is_pngL
elif self.image_depth==8:
#limited options:
if self.encoding=="grayscale":
assert "png/L" in self.common_encodings
return self.encoding_is_pngL
assert "png/P" in self.common_encodings
return self.encoding_is_pngP
elif self.strict and self.encoding!="auto":
#honour strict flag
if self.encoding=="rgb":
#choose between rgb32 and rgb24 already
#as alpha support does not change without going through this method
if self._want_alpha and "rgb32" in self.common_encodings:
return self.encoding_is_rgb32
assert "rgb24" in self.common_encodings
return self.encoding_is_rgb24
return self.get_strict_encoding
elif self._want_alpha or self.is_tray:
if self.encoding in ("rgb", "rgb32") and "rgb32" in self.common_encodings:
return self.encoding_is_rgb32
if self.encoding in ("png", "png/P"):
#chosen encoding does alpha, stick to it:
#(prevents alpha bleeding artifacts,
# as different encoders may encode alpha differently)
return self.get_strict_encoding
if self.encoding=="grayscale":
return self.encoding_is_grayscale
#choose an alpha encoding and keep it?
return self.get_transparent_encoding
elif self.encoding=="rgb":
#if we're here we don't need alpha, so try rgb24 first:
if "rgb24" in self.common_encodings:
return self.encoding_is_rgb24
if "rgb32" in self.common_encodings:
return self.encoding_is_rgb32
return self.get_best_encoding_impl_default()
def get_best_encoding_impl_default(self):
#stick to what is specified or use rgb for small regions:
if self.encoding=="auto":
return self.get_auto_encoding
if self.encoding=="grayscale":
return self.encoding_is_grayscale
return self.get_current_or_rgb
def hardcoded_encoding(self, *_args):
return HARDCODED_ENCODING
def encoding_is_hint(self, *_args):
return self._encoding_hint
def encoding_is_mmap(self, *_args):
return "mmap"
def encoding_is_pngL(self, *_args):
return "png/L"
def encoding_is_pngP(self, *_args):
return "png/P"
def encoding_is_rgb32(self, *_args):
return "rgb32"
def encoding_is_rgb24(self, *_args):
return "rgb24"
def get_strict_encoding(self, *_args):
return self.encoding
def encoding_is_grayscale(self, *args):
e = self.get_auto_encoding(*args) #pylint: disable=no-value-for-parameter
if e.startswith("rgb") or e.startswith("png"):
return "png/L"
return e
def get_transparent_encoding(self, w, h, speed, quality, current_encoding):
#small areas prefer rgb, also when high speed and high quality
if current_encoding in TRANSPARENCY_ENCODINGS:
return current_encoding
pixel_count = w*h
depth = self.image_depth
co = self.common_encodings
def canuse(e):
return e in co and e in TRANSPARENCY_ENCODINGS
if canuse("rgb32") and (
pixel_count<self._rgb_auto_threshold or
(quality>=90 and speed>=90) or
(depth>24 and self.client_bit_depth>24)
):
#the only encoding that can do higher bit depth at present
return "rgb32"
if canuse("webp") and depth in (24, 32) and 16383>=w>=2 and 16383>=h>=2:
return "webp"
for x in TRANSPARENCY_ENCODINGS:
if x in self.common_encodings:
return x
#so we don't have an encoding that does transparency...
return self.get_auto_encoding(w, h, speed, quality)
def get_auto_encoding(self, w, h, speed, quality, *_args):
co = self.common_encodings
depth = self.image_depth
if depth>24 and "rgb32" in co and self.client_bit_depth>24:
#the only encoding that can do higher bit depth at present
return "rgb32"
if w*h<self._rgb_auto_threshold:
return "rgb24"
if self.enc_nvjpeg and "jpeg" in co and w>=16 and h>=16 and quality<100:
return "jpeg"
if depth in (24, 32) and "webp" in co and 16383>=w>=2 and 16383>=h>=2:
return "webp"
if "png" in co and ((quality>=80 and speed<80) or depth<=16):
return "png"
if "jpeg" in co and w>=2 and h>=2:
return "jpeg"
return next(x for x in co if x!="rgb")
def get_current_or_rgb(self, pixel_count, *_args):
if pixel_count<self._rgb_auto_threshold: