-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathvideo_compress.py
2700 lines (2519 loc) · 126 KB
/
video_compress.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
# This file is part of Xpra.
# Copyright (C) 2013-2024 Antoine Martin <[email protected]>
# 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
import operator
from math import sqrt, ceil
from functools import reduce
from time import monotonic
from typing import Any
from collections.abc import Callable, Iterable, Sequence
from xpra.os_util import gi_import
from xpra.net.compression import Compressed, LargeStructure
from xpra.codecs.constants import TransientCodecException, RGB_FORMATS, PIXEL_SUBSAMPLING
from xpra.codecs.image import ImageWrapper
from xpra.server.window.compress import (
WindowSource, DelayedRegions, get_encoder_type,
STRICT_MODE, LOSSLESS_WINDOW_TYPES,
DOWNSCALE_THRESHOLD, DOWNSCALE, TEXT_QUALITY,
COMPRESS_FMT_PREFIX, COMPRESS_FMT_SUFFIX, COMPRESS_FMT,
LOG_ENCODERS,
)
from xpra.util.rectangle import rectangle, merge_all
from xpra.server.window.video_subregion import VideoSubregion, VIDEO_SUBREGION
from xpra.server.window.video_scoring import get_pipeline_score
from xpra.codecs.constants import PREFERRED_ENCODING_ORDER, EDGE_ENCODING_ORDER, preforder, CSCSpec
from xpra.codecs.loader import has_codec
from xpra.common import roundup
from xpra.util.parsing import parse_scaling_value
from xpra.util.objects import typedict
from xpra.util.str_fn import csv, print_nested_dict, memoryview_to_bytes
from xpra.util.env import envint, envbool, first_time
from xpra.log import Logger
GLib = gi_import("GLib")
log = Logger("encoding")
csclog = Logger("csc")
scorelog = Logger("score")
scalinglog = Logger("scaling")
sublog = Logger("subregion")
videolog = Logger("video")
avsynclog = Logger("av-sync")
scrolllog = Logger("scroll")
compresslog = Logger("compress")
refreshlog = Logger("refresh")
regionrefreshlog = Logger("regionrefresh")
gstlog = Logger("gstreamer")
TEXT_USE_VIDEO = envbool("XPRA_TEXT_USE_VIDEO", False)
MAX_NONVIDEO_PIXELS = envint("XPRA_MAX_NONVIDEO_PIXELS", 1024*4)
MIN_VIDEO_FPS = envint("XPRA_MIN_VIDEO_FPS", 10)
MIN_VIDEO_EVENTS = envint("XPRA_MIN_VIDEO_EVENTS", 20)
ENCODE_QUEUE_MIN_GAP = envint("XPRA_ENCODE_QUEUE_MIN_GAP", 5)
VIDEO_TIMEOUT = envint("XPRA_VIDEO_TIMEOUT", 10)
VIDEO_NODETECT_TIMEOUT = envint("XPRA_VIDEO_NODETECT_TIMEOUT", 10*60)
FORCE_CSC_MODE = os.environ.get("XPRA_FORCE_CSC_MODE", "") # ie: "YUV444P"
if FORCE_CSC_MODE and FORCE_CSC_MODE not in RGB_FORMATS and FORCE_CSC_MODE not in PIXEL_SUBSAMPLING:
log.warn("ignoring invalid CSC mode specified: %s", FORCE_CSC_MODE)
FORCE_CSC_MODE = ""
FORCE_CSC = bool(FORCE_CSC_MODE) or envbool("XPRA_FORCE_CSC", False)
SCALING = envbool("XPRA_SCALING", True)
SCALING_HARDCODED = parse_scaling_value(os.environ.get("XPRA_SCALING_HARDCODED", ""))
SCALING_PPS_TARGET = envint("XPRA_SCALING_PPS_TARGET", 25*1920*1080)
SCALING_MIN_PPS = envint("XPRA_SCALING_MIN_PPS", 25*320*240)
DEFAULT_SCALING_OPTIONS = (1, 10), (1, 5), (1, 4), (1, 3), (1, 2), (2, 3), (1, 1)
ALWAYS_FREEZE = envbool("XPRA_IMAGE_ALWAYS_FREEZE", False)
def parse_scaling_options_str(scaling_options_str: str) -> tuple:
if not scaling_options_str:
return ()
# parse 1/10,1/5,1/4,1/3,1/2,2/3,1/1
# or even: 1:10, 1:5, ...
vs_options = []
for option in scaling_options_str.split(","):
try:
if option.find("%") > 0:
v = float(option[:option.find("%")])*100
vs_options.append(v.as_integer_ratio())
elif option.find("/") < 0:
v = float(option)
vs_options.append(v.as_integer_ratio())
else:
num, den = option.strip().split("/")
vs_options.append((int(num), int(den)))
except ValueError:
scalinglog.warn("Warning: invalid scaling string '%s'", option.strip())
if vs_options:
return tuple(vs_options)
return ()
SCALING_OPTIONS = parse_scaling_options_str(os.environ.get("XPRA_SCALING_OPTIONS", "")) or DEFAULT_SCALING_OPTIONS
scalinglog("scaling options: SCALING=%s, HARDCODED=%s, PPS_TARGET=%i, MIN_PPS=%i, OPTIONS=%s",
SCALING, SCALING_HARDCODED, SCALING_PPS_TARGET, SCALING_MIN_PPS, SCALING_OPTIONS)
DEBUG_VIDEO_CLEAN = envbool("XPRA_DEBUG_VIDEO_CLEAN", False)
FORCE_AV_DELAY = envint("XPRA_FORCE_AV_DELAY", -1)
AV_SYNC_DEFAULT = envbool("XPRA_AV_SYNC_DEFAULT", False)
B_FRAMES = envbool("XPRA_B_FRAMES", True)
VIDEO_SKIP_EDGE = envbool("XPRA_VIDEO_SKIP_EDGE", False)
SCROLL_MIN_PERCENT = max(1, min(100, envint("XPRA_SCROLL_MIN_PERCENT", 30)))
MIN_SCROLL_IMAGE_SIZE = envint("XPRA_MIN_SCROLL_IMAGE_SIZE", 128)
STREAM_MODE = os.environ.get("XPRA_STREAM_MODE", "auto")
STREAM_CONTENT_TYPES = os.environ.get("XPRA_STREAM_CONTENT_TYPES", "desktop,video").split(",")
GSTREAMER_X11_TIMEOUT = envint("XPRA_GSTREAMER_X11_TIMEOUT", 500)
SAVE_VIDEO_PATH = os.environ.get("XPRA_SAVE_VIDEO_PATH", "")
SAVE_VIDEO_STREAMS = envbool("XPRA_SAVE_VIDEO_STREAMS", False)
SAVE_VIDEO_FRAMES = os.environ.get("XPRA_SAVE_VIDEO_FRAMES")
if SAVE_VIDEO_FRAMES not in ("png", "jpeg", None):
log.warn("Warning: invalid value for 'XPRA_SAVE_VIDEO_FRAMES'")
log.warn(" only 'png' or 'jpeg' are allowed")
SAVE_VIDEO_FRAMES = None
COMPRESS_SCROLL_FMT = COMPRESS_FMT_PREFIX+" as %3i rectangles (%5iKB to 0KB)"+COMPRESS_FMT_SUFFIX
def get_pipeline_score_info(score, scaling,
csc_scaling, csc_width: int, csc_height: int, csc_spec,
enc_in_format, encoder_scaling, enc_width: int, enc_height: int, encoder_spec)\
-> dict[str, Any]:
def specinfo(x):
try:
return x.codec_type
except AttributeError:
return repr(x)
ei = {
"" : specinfo(encoder_spec),
"width" : enc_width,
"height" : enc_height,
}
if encoder_scaling != (1, 1):
ei["scaling"] = encoder_scaling
pi : dict[str, Any] = {
"score" : score,
"format" : str(enc_in_format),
"encoder" : ei,
}
if scaling != (1, 1):
pi["scaling"] = scaling
if csc_spec:
csci : dict[str, Any] = {
"" : specinfo(csc_spec),
"width" : csc_width,
"height" : csc_height,
}
if csc_scaling != (1, 1):
csci["scaling"] = csc_scaling
pi["csc"] = csci
else:
pi["csc"] = "None"
return pi
class WindowVideoSource(WindowSource):
"""
A WindowSource that handles video codecs.
"""
def __init__(self, *args):
self.supports_scrolling: bool = False
# this will call init_vars():
super().__init__(*args)
self.scroll_min_percent: int = self.encoding_options.intget("scrolling.min-percent", SCROLL_MIN_PERCENT)
self.scroll_preference: int = self.encoding_options.intget("scrolling.preference", 100)
self.supports_video_b_frames: Sequence[str] = self.encoding_options.strtupleget("video_b_frames", ())
self.video_max_size = self.encoding_options.inttupleget("video_max_size", (8192, 8192), 2, 2)
self.video_stream_file = None
def __repr__(self) -> str:
return f"WindowVideoSource({self.wid} : {self.window_dimensions})"
def init_vars(self) -> None:
super().init_vars()
# these constraints get updated with real values
# when we construct the video pipeline:
self.min_w: int = 8
self.min_h: int = 8
self.max_w: int = 16384
self.max_h: int = 16384
self.width_mask: int = 0xFFFF
self.height_mask: int = 0xFFFF
self.actual_scaling = (1, 1)
self.last_pipeline_params : tuple = ()
self.last_pipeline_scores : tuple = ()
self.last_pipeline_time: int = 0
self.video_subregion = VideoSubregion(self.refresh_subregion, self.auto_refresh_delay, VIDEO_SUBREGION)
self.video_subregion.supported = VIDEO_SUBREGION
self.video_encodings: Sequence[str] = ()
self.common_video_encodings: Sequence[str] = ()
self.non_video_encodings: Sequence[str] = ()
self.video_fallback_encodings: dict = {}
self.edge_encoding: str = ""
self.start_video_frame: int = 0
self.gstreamer_timer: int = 0
self.video_encoder_timer: int = 0
self.b_frame_flush_timer: int = 0
self.b_frame_flush_data : tuple = ()
self.encode_from_queue_timer: int = 0
self.encode_from_queue_due = 0
self.scroll_data = None
self.last_scroll_time = 0.0
self.stream_mode = STREAM_MODE
self.gstreamer_pipeline = None
self._csc_encoder = None
self._video_encoder = None
self._last_pipeline_check = 0
def do_init_encoders(self) -> None:
super().do_init_encoders()
self._csc_encoder = None
self._video_encoder = None
self._last_pipeline_check = 0
def add(enc, encode_fn):
self.insert_encoder(enc, enc, encode_fn)
if has_codec("csc_libyuv"):
# need libyuv to be able to handle 'grayscale' video:
# (to convert ARGB to grayscale)
add("grayscale", self.video_encode)
if self._mmap_size > 0:
self.non_video_encodings = ()
self.common_video_encodings = ()
return
# make sure we actually have encoders for these:
vencs = self.video_helper.get_encodings()
self.video_encodings = preforder(vencs)
self.common_video_encodings = preforder(set(self.video_encodings) & set(self.core_encodings))
log(f"do_init_encoders() video encodings({vencs})={self.video_encodings}")
log(f"do_init_encoders() common video encodings={self.common_video_encodings}")
video_enabled = []
for x in self.common_video_encodings:
self.append_encoder(x, self.video_encode)
video_enabled.append(x)
# video_encode() is used for more than just video encoders:
# (always enable it and let it fall through)
add("auto", self.video_encode)
add("stream", self.video_encode)
# these are used for non-video areas, ensure "jpeg" is used if available
# as we may be dealing with large areas still, and we want speed:
enc_options = set(self.server_core_encodings) & set(self._encoders.keys())
nv_common = (enc_options & set(self.core_encodings)) - set(self.video_encodings)
self.non_video_encodings = preforder(nv_common)
log("do_init_encoders()")
log(f" server core encodings={self.server_core_encodings}")
log(f" client core encodings={self.core_encodings}")
log(f" video encodings={self.video_encodings}")
log(f" common video encodings={self.common_video_encodings}")
log(f" non video encodings={self.non_video_encodings}")
if "scroll" in self.server_core_encodings:
add("scroll", self.scroll_encode)
def do_set_auto_refresh_delay(self, min_delay, delay) -> None:
super().do_set_auto_refresh_delay(min_delay, delay)
r = self.video_subregion
if r:
r.set_auto_refresh_delay(self.base_auto_refresh_delay)
def update_av_sync_frame_delay(self) -> None:
self.av_sync_frame_delay = 0
ve = self._video_encoder
if ve:
# how many frames are buffered in the encoder, if any:
d = ve.get_info().get("delayed", 0)
if d > 0:
# clamp the batch delay to a reasonable range:
frame_delay = min(100, max(10, self.batch_config.delay))
self.av_sync_frame_delay += frame_delay * d
avsynclog("update_av_sync_frame_delay() video encoder=%s, delayed frames=%i, frame delay=%i",
ve, d, self.av_sync_frame_delay)
self.may_update_av_sync_delay()
def get_property_info(self) -> dict[str, Any]:
i = super().get_property_info()
if self.scaling_control is None:
i["scaling.control"] = "auto"
else:
i["scaling.control"] = self.scaling_control
i["scaling"] = self.scaling or (1, 1)
return i
def get_info(self) -> dict[str, Any]:
info = super().get_info()
sr = self.video_subregion
if sr:
sri = sr.get_info()
sri["video-mode"] = self.subregion_is_video()
info["video_subregion"] = sri
info["scaling"] = self.actual_scaling
info["video-max-size"] = self.video_max_size
info["stream-mode"] = self.stream_mode
def addcinfo(prefix, x):
if not x:
return
with log.trap_error(f"Error collecting codec information from {x}"):
i = x.get_info()
i[""] = x.get_type()
info[prefix] = i
addcinfo("csc", self._csc_encoder)
addcinfo("encoder", self._video_encoder)
info.setdefault("encodings", {}).update({
"non-video" : self.non_video_encodings,
"video" : self.common_video_encodings,
"edge" : self.edge_encoding,
})
einfo = {
"pipeline_param" : self.get_pipeline_info(),
"scrolling" : {
"enabled" : self.supports_scrolling,
"min-percent" : self.scroll_min_percent,
"preference" : self.scroll_preference,
"event" : int(self.last_scroll_event*1000),
"time" : int(self.last_scroll_time*1000),
}
}
if self._last_pipeline_check > 0:
einfo["pipeline_last_check"] = int(1000*(monotonic()-self._last_pipeline_check))
lps = self.last_pipeline_scores
if lps:
popts : dict[int, dict[str, Any]] = {}
for i, lp in enumerate(lps):
popts[i] = get_pipeline_score_info(*lp)
einfo["pipeline_option"] = popts
info.setdefault("encoding", {}).update(einfo)
return info
def get_pipeline_info(self) -> dict[str, Any]:
lp = self.last_pipeline_params
if not lp:
return {}
encoding, width, height, src_format = lp
return {
"encoding" : encoding,
"dimensions" : (width, height),
"src_format" : src_format
}
def suspend(self) -> None:
super().suspend()
# we'll create a new video pipeline when resumed:
self.cleanup_codecs()
def cleanup(self) -> None:
super().cleanup()
self.cleanup_codecs()
self.stop_gstreamer_pipeline()
def cleanup_codecs(self) -> None:
""" Video encoders (x264, nvenc and vpx) and their csc helpers
require us to run cleanup code to free the memory they use.
We have to do this from the encode thread to be safe.
(the encoder and csc module may be in use by that thread)
"""
self.cancel_video_encoder_flush()
self.video_context_clean()
def video_context_clean(self) -> None:
""" Calls clean() from the encode thread """
csce = self._csc_encoder
ve = self._video_encoder
if csce or ve:
if DEBUG_VIDEO_CLEAN:
log.warn("video_context_clean() for wid %i: %s and %s", self.wid, csce, ve, backtrace=True)
self._csc_encoder = None
self._video_encoder = None
def clean():
if DEBUG_VIDEO_CLEAN:
log.warn("video_context_clean() done")
self.csc_clean(csce)
self.ve_clean(ve)
self.call_in_encode_thread(False, clean)
# noinspection PyMethodMayBeStatic
def csc_clean(self, csce) -> None:
if csce:
csce.clean()
def ve_clean(self, ve) -> None:
self.cancel_video_encoder_timer()
if ve:
ve.clean()
# only send eos if this video encoder is still current,
# (otherwise, sending the new stream will have taken care of it already,
# and sending eos then would close the new stream, not the old one!)
if self._video_encoder == ve:
log("sending eos for wid %i", self.wid)
self.queue_packet(("eos", self.wid))
if SAVE_VIDEO_STREAMS:
self.close_video_stream_file()
def close_video_stream_file(self) -> None:
vsf = self.video_stream_file
if vsf:
self.video_stream_file = None
with log.trap_error(f"Error closing video stream file {vsf}"):
vsf.close()
def ui_cleanup(self) -> None:
super().ui_cleanup()
self.video_subregion = None
def set_new_encoding(self, encoding : str, strict=None) -> None:
if self.encoding != encoding:
# ensure we re-init the codecs asap:
self.cleanup_codecs()
super().set_new_encoding(encoding, strict)
def insert_encoder(self, encoder_name : str, encoding : str, encode_fn : Callable) -> None:
super().insert_encoder(encoder_name, encoding, encode_fn)
# we don't want to use nvjpeg as fallback,
# because it requires a GPU context
# and the fallback should be reliable.
# also, we only want picture encodings here,
# and filtering using EDGE_ENCODING_ORDER gives us that.
if encoder_name != "nvjpeg" and encoding in EDGE_ENCODING_ORDER:
self.video_fallback_encodings.setdefault(encoding, []).insert(0, encode_fn)
def update_encoding_selection(self, encoding="", exclude=None, init=False) -> None:
# override so we don't use encodings that don't have valid csc modes:
log("wvs.update_encoding_selection(%s, %s, %s) full_csc_modes=%s", encoding, exclude, init, self.full_csc_modes)
if exclude is None:
exclude = []
videolog(f"encoding={encoding}, video_encodings={self.video_encodings}, core_encodings={self.core_encodings}")
for x in self.video_encodings:
if x not in self.core_encodings:
log("video encoding %s not in core encodings", x)
exclude.append(x)
continue
csc_modes = self.full_csc_modes.strtupleget(x)
if (not csc_modes or x not in self.core_encodings) and first_time(f"nocsc-{x}-{self.wid}"):
exclude.append(x)
msg_args = ("Warning: client does not support any csc modes with %s on window %i", x, self.wid)
if x == "jpega" and not self.supports_transparency:
log(f"skipping {x} since client does not support transparency")
elif not init and first_time(f"no-csc-{x}-{self.wid}"):
log.warn(*msg_args)
else:
log(*msg_args)
log(" csc modes=%", self.full_csc_modes)
self.common_video_encodings = preforder(set(self.video_encodings) & set(self.core_encodings))
videolog("update_encoding_selection: common_video_encodings=%s, csc_encoder=%s, video_encoder=%s",
self.common_video_encodings, self._csc_encoder, self._video_encoder)
if encoding in ("stream", "auto", "grayscale"):
vh = self.video_helper
if encoding in ("auto", "stream") and self.content_type in STREAM_CONTENT_TYPES and vh:
accel = vh.get_gpu_encodings()
common_accel = preforder(set(self.common_video_encodings) & set(accel.keys()))
videolog(f"gpu {accel=} - {common_accel=}")
if common_accel:
encoding = "stream"
accel_types: set[str] = set()
for gpu_encoding in common_accel:
for accel_option in accel.get(gpu_encoding, ()):
# 'gstreamer-vah264lpenc' -> 'gstreamer'
accel_types.add(accel_option.codec_type.split("-", 1)[0])
videolog(f"gpu encoder types: {accel_types}")
self.stream_mode = STREAM_MODE
# switch to GStreamer mode if all the GPU accelerated options require it:
if self.stream_mode == "auto" and len(accel_types) == 1 and tuple(accel_types)[0] == "gstreamer":
self.stream_mode = "gstreamer"
if first_time(f"gpu-stream-{self.wid}"):
videolog.info(f"found GPU accelerated encoders for: {csv(common_accel)}")
videolog.info(f"switching to {encoding!r} encoding for {self.content_type!r} window {self.wid}")
if self.stream_mode == "gstreamer":
videolog.info("using 'gstreamer' stream mode")
super().update_encoding_selection(encoding, exclude, init)
self.supports_scrolling = "scroll" in self.common_encodings
def do_set_client_properties(self, properties: typedict) -> None:
# client may restrict csc modes for specific windows
self.supports_scrolling = "scroll" in self.common_encodings
self.scroll_min_percent = properties.intget("scrolling.min-percent", self.scroll_min_percent)
self.scroll_preference = properties.intget("scrolling.preference", self.scroll_preference)
if VIDEO_SUBREGION:
self.video_subregion.supported = properties.boolget("encoding.video_subregion", True)
if properties.get("scaling.control") is not None:
self.scaling_control = max(0, min(100, properties.intget("scaling.control", 0)))
super().do_set_client_properties(properties)
# encodings may have changed, so redo this:
nv_common = set(self.picture_encodings) & set(self.core_encodings)
log("common non-video (%s & %s)=%s", self.picture_encodings, self.core_encodings, nv_common)
self.non_video_encodings = preforder(nv_common)
if not VIDEO_SKIP_EDGE:
try:
self.edge_encoding = next(x for x in EDGE_ENCODING_ORDER if x in self.non_video_encodings)
except StopIteration:
self.edge_encoding = ""
log("do_set_client_properties(%s)", properties)
log(" full_csc_modes=%s, video_subregion=%s, non_video_encodings=%s, edge_encoding=%s, scaling_control=%s",
self.full_csc_modes, self.video_subregion.supported,
self.non_video_encodings, self.edge_encoding, self.scaling_control)
def get_best_encoding_impl_default(self) -> Callable:
log("get_best_encoding_impl_default() window_type=%s, encoding=%s", self.window_type, self.encoding)
if self.is_tray:
log("using default for tray")
return super().get_best_encoding_impl_default()
if self.encoding == "stream":
log("using stream encoding")
return self.get_best_encoding_video
if self.window_type.intersection(LOSSLESS_WINDOW_TYPES):
log("using default for lossless window type %s", self.window_type)
return super().get_best_encoding_impl_default()
if self.encoding != "grayscale" or has_codec("csc_libyuv"):
if self.common_video_encodings or self.supports_scrolling:
log("using video encoding")
return self.get_best_encoding_video
log("using default best encoding")
return super().get_best_encoding_impl_default()
def get_best_encoding_video(self, w: int, h: int, options, current_encoding : str) -> str:
"""
decide whether we send a full window update using the video encoder,
or if a separate small region(s) is a better choice
"""
def nonvideo(qdiff=0, info=""):
if qdiff:
quality = options.get("quality", self._current_quality) + qdiff
options["quality"] = max(self._fixed_min_quality, min(self._fixed_max_quality, quality))
videolog("nonvideo(%s, %s)", qdiff, info)
return WindowSource.get_auto_encoding(self, w, h, options)
# log("get_best_encoding_video%s non_video_encodings=%s, common_video_encodings=%s, supports_scrolling=%s",
# (pixel_count, ww, wh, speed, quality, current_encoding),
# self.non_video_encodings, self.common_video_encodings, self.supports_scrolling)
if not self.non_video_encodings:
return current_encoding
if not self.common_video_encodings and not self.supports_scrolling:
return nonvideo(info="no common video encodings or scrolling")
if self.is_tray:
return nonvideo(100, "system tray")
text_hint = self.content_type.find("text") >= 0
if text_hint and not TEXT_USE_VIDEO:
return nonvideo(100, info="text content-type")
# ensure the dimensions we use for decision-making are the ones actually used:
cww = w & self.width_mask
cwh = h & self.height_mask
if cww < 64 or cwh < 64:
return nonvideo(info="area is too small")
if self.encoding == "stream":
return current_encoding
video_hint = int(self.content_type.find("video") >= 0)
if self.pixel_format:
# if we have a hardware video encoder, use video more:
self.update_pipeline_scores()
for i, score_data in enumerate(self.last_pipeline_scores):
encoder_spec = score_data[-1]
if encoder_spec.gpu_cost > encoder_spec.cpu_cost:
videolog(f"found GPU accelerated encoder {encoder_spec}")
video_hint += 1+int(i == 0)
break
rgbmax = self._rgb_auto_threshold
videomin = cww*cwh // (1+video_hint*2)
sr = self.video_subregion.rectangle
if sr:
videomin = min(videomin, sr.width * sr.height)
rgbmax = min(rgbmax, sr.width*sr.height//2)
elif text_hint:
# TEXT_USE_VIDEO must be set,
# but only use video if the whole area changed:
videomin = cww*cwh
else:
videomin = min(640*480, cww*cwh) // (1+video_hint*2)
# log(f"ww={ww}, wh={wh}, rgbmax={rgbmax}, videohint={video_hint},
# videomin={videomin}, sr={sr}, pixel_count={pixel_count}")
pixel_count = w*h
if pixel_count <= rgbmax:
return nonvideo(info=f"low pixel count {pixel_count}")
if current_encoding not in ("auto", "grayscale") and current_encoding not in self.common_video_encodings:
return nonvideo(info=f"{current_encoding} not a supported video encoding")
if cww < self.min_w or cww > self.max_w or cwh < self.min_h or cwh > self.max_h:
return nonvideo(info="size out of range for video encoder")
now = monotonic()
if now-self.statistics.last_packet_time > 1:
return nonvideo(info="no recent updates")
if now-self.statistics.last_resized < 0.350:
return nonvideo(info="resized recently")
if sr and ((sr.width & self.width_mask) != cww or (sr.height & self.height_mask) != cwh):
# we have a video region, and this is not it, so don't use video
# raise the quality as the areas around video tend to not be updating as quickly
return nonvideo(30, "not the video region")
if not video_hint and not self.is_shadow:
if now-self.global_statistics.last_congestion_time > 5:
lde = tuple(self.statistics.last_damage_events)
lim = now-4
pixels_last_4secs = sum(w*h for when, _, _, w, h in lde if when > lim)
if pixels_last_4secs < ((3+text_hint*6)*videomin):
return nonvideo(info="not enough frames")
lim = now-1
pixels_last_sec = sum(w*h for when, _, _, w, h in lde if when > lim)
if pixels_last_sec < pixels_last_4secs//8:
# framerate is dropping?
return nonvideo(30, "framerate lowered")
# calculate the threshold for using video vs small regions:
speed = options.get("speed", self._current_speed)
factors = (
# speed multiplier:
max(1, (speed-75)/5.0),
# OR windows tend to be static:
1 + int(self.is_OR or self.is_tray)*2,
# gradual discount the first 9 frames, as the window may be temporary:
max(1, 10-self._sequence),
# if we have a video encoder already, make it more likely we'll use it:
1.0 / (int(bool(self._video_encoder)) + 1),
)
max_nvp = int(reduce(operator.mul, factors, MAX_NONVIDEO_PIXELS))
if pixel_count <= max_nvp:
# below threshold
return nonvideo(info=f"not enough pixels: {pixel_count}<{max_nvp}")
return current_encoding
def get_best_nonvideo_encoding(self, ww: int, wh: int, options: dict,
current_encoding="", encoding_options=()) -> str:
if self.encoding == "grayscale":
return self.encoding_is_grayscale(ww, wh, options, current_encoding or self.encoding)
# if we're here, then the window has no alpha (or the client cannot handle alpha)
# and we can ignore the current encoding
encoding_options = encoding_options or self.non_video_encodings
depth = self.image_depth
if (depth == 8 and "png/P" in encoding_options) or self.encoding == "png/P":
return "png/P"
if self.encoding == "png/L":
return "png/L"
if self._mmap_size > 0:
return "mmap"
return super().do_get_auto_encoding(ww, wh, options, current_encoding or self.encoding, encoding_options)
def do_damage(self, ww: int, wh: int, x: int, y: int, w: int, h: int, options: dict) -> None:
if ww >= 64 and wh >= 64 and self.encoding == "stream" and self.stream_mode == "gstreamer":
# in this mode, we start a pipeline once
# and let it submit packets, bypassing all the usual logic:
if self.gstreamer_pipeline or self.start_gstreamer_pipeline():
gp = self.gstreamer_pipeline
self.cancel_gstreamer_timer()
if gp:
self.gstreamer_timer = GLib.timeout_add(GSTREAMER_X11_TIMEOUT, self.gstreamer_nodamage)
return
vs = self.video_subregion
if vs:
r = vs.rectangle
if r and r.intersects(x, y, w, h):
# the damage will take care of scheduling it again
vs.cancel_refresh_timer()
super().do_damage(ww, wh, x, y, w, h, options)
def gstreamer_nodamage(self) -> None:
gstlog("gstreamer_nodamage() stopping")
self.gstreamer_timer = 0
self.stop_gstreamer_pipeline()
def cancel_gstreamer_timer(self) -> None:
gt = self.gstreamer_timer
if gt:
GLib.source_remove(gt)
def start_gstreamer_pipeline(self) -> bool:
from xpra.gstreamer.common import plugin_str
from xpra.codecs.gstreamer.capture import capture_and_encode
attrs = {
"show-pointer": False,
"do-timestamp": True,
"use-damage": False,
}
try:
xid = self.window.get_property("xid")
except (TypeError, AttributeError):
xid = 0
if xid:
attrs["xid"] = xid
capture_element = plugin_str("ximagesrc", attrs)
w, h = self.window_dimensions
self.gstreamer_pipeline = capture_and_encode(capture_element, self.encoding, self.full_csc_modes, w, h)
if not self.gstreamer_pipeline:
return False
self.gstreamer_pipeline.connect("new-image", self.new_gstreamer_frame)
self.gstreamer_pipeline.start()
gstlog("start_gstreamer_pipeline() %s started", self.gstreamer_pipeline)
return True
def stop_gstreamer_pipeline(self) -> None:
gp = self.gstreamer_pipeline
gstlog("stop_gstreamer_pipeline() gstreamer_pipeline=%s", gp)
if gp:
self.gstreamer_pipeline = None
gp.stop()
def new_gstreamer_frame(self, _capture_pipeline, coding: str, data, client_info: dict) -> None:
gstlog(f"new_gstreamer_frame: {coding}")
if not self.window.is_managed():
return
gp = self.gstreamer_pipeline
if gp and (LOG_ENCODERS or compresslog.is_debug_enabled()):
client_info["encoder"] = gp.encoder
self.direct_queue_draw(coding, data, client_info)
GLib.idle_add(self.gstreamer_continue_damage)
def gstreamer_continue_damage(self) -> None:
# ensures that more damage events will be emitted
self.ui_thread_check()
self.window.acknowledge_changes()
def update_window_dimensions(self, ww: int, wh: int) -> None:
super().update_window_dimensions(ww, wh)
self.stop_gstreamer_pipeline()
def cancel_damage(self, limit: int = 0):
self.cancel_encode_from_queue()
self.free_encode_queue_images()
vsr = self.video_subregion
if vsr:
vsr.cancel_refresh_timer()
self.free_scroll_data()
self.last_scroll_time = 0
super().cancel_damage(limit)
self.cancel_gstreamer_timer()
self.stop_gstreamer_pipeline()
# we must clean the video encoder to ensure
# we will resend a key frame because we may be missing a frame
self.cleanup_codecs()
def full_quality_refresh(self, damage_options: dict) -> None:
vs = self.video_subregion
if vs and vs.rectangle:
if vs.detection:
# reset the video region on full quality refresh
vs.reset()
else:
# keep the region, but cancel the refresh:
vs.cancel_refresh_timer()
self.free_scroll_data()
self.last_scroll_time = 0
if self.non_video_encodings:
# refresh the whole window in one go:
damage_options["novideo"] = True
super().full_quality_refresh(damage_options)
def timer_full_refresh(self) -> None:
self.free_scroll_data()
self.last_scroll_time = 0
super().timer_full_refresh()
def quality_changed(self, window, *args) -> bool:
super().quality_changed(window, args)
self.video_context_clean()
return True
def speed_changed(self, window, *args) -> bool:
super().speed_changed(window, args)
self.video_context_clean()
return True
def client_decode_error(self, error: int | float, message: str) -> None:
# maybe the stream is now corrupted..
self.cleanup_codecs()
super().client_decode_error(error, message)
def get_refresh_exclude(self) -> rectangle | None:
# exclude video region (if any) from lossless refresh:
return self.video_subregion.rectangle
def refresh_subregion(self, regions) -> bool:
# callback from video subregion to trigger a refresh of some areas
if not regions:
regionrefreshlog("refresh_subregion(%s) nothing to refresh", regions)
return False
if not self.can_refresh():
regionrefreshlog("refresh_subregion(%s) cannot refresh", regions)
return False
now = monotonic()
if now-self.global_statistics.last_congestion_time < 5:
regionrefreshlog("refresh_subregion(%s) skipping refresh due to congestion", regions)
return False
self.flush_video_encoder_now()
encoding = self.auto_refresh_encodings[0]
options = self.get_refresh_options()
regionrefreshlog("refresh_subregion(%s) using %s and %s", regions, encoding, options)
self.do_send_regions(now, regions, encoding, options,
get_best_encoding=self.get_refresh_subregion_encoding)
return True
def get_refresh_subregion_encoding(self, *_args) -> str:
ww, wh = self.window_dimensions
w, h = ww, wh
vr = self.video_subregion.rectangle
# could have been cleared by another thread:
if vr:
w, h = vr.width, vr.height
options = {
"speed": self.refresh_speed,
"quality": self.refresh_quality,
}
return self.get_best_nonvideo_encoding(w, h, options,
self.auto_refresh_encodings[0], self.auto_refresh_encodings)
def remove_refresh_region(self, region: rectangle) -> None:
# override so we can update the subregion timers / regions tracking:
super().remove_refresh_region(region)
self.video_subregion.remove_refresh_region(region)
def add_refresh_region(self, region: rectangle) -> int:
# Note: this does not run in the UI thread!
# returns the number of pixels in the region update
# don't refresh the video region as part of normal refresh,
# use subregion refresh for that
sarr = super().add_refresh_region
vr = self.video_subregion.rectangle
if vr is None:
# no video region, normal code path:
return sarr(region)
if vr.contains_rect(region):
# all of it is in the video region:
self.video_subregion.add_video_refresh(region)
return 0
ir = vr.intersection_rect(region)
if ir is None:
# region is outside video region, normal code path:
return sarr(region)
# add intersection (rectangle in video region) to video refresh:
self.video_subregion.add_video_refresh(ir)
# add any rectangles not in the video region
# (if any: keep track if we actually added anything)
return sum(sarr(r) for r in region.subtract_rect(vr))
def matches_video_subregion(self, width: int, height: int):
vr = self.video_subregion.rectangle
if not vr:
return None
mw = abs(width - vr.width) & self.width_mask
mh = abs(height - vr.height) & self.height_mask
if mw != 0 or mh != 0:
return None
return vr
def subregion_is_video(self) -> bool:
vs = self.video_subregion
if not vs:
return False
vr = vs.rectangle
if not vr:
return False
events_count = self.statistics.damage_events_count - vs.set_at
min_video_events = MIN_VIDEO_EVENTS
min_video_fps = MIN_VIDEO_FPS
if self.content_type.find("video") >= 0:
min_video_events //= 2
min_video_fps //= 2
if events_count < min_video_events:
return False
if vs.fps < min_video_fps:
return False
return True
def send_regions(self, damage_time: float, regions: Sequence[rectangle], coding: str, options: dict):
"""
Overridden here so that we can try to intercept the `video_subregion` if one exists.
"""
vr = self.video_subregion.rectangle
# overrides the default method for finding the encoding of a region,
# so we can ensure we don't use the video encoder when we don't want to:
def send_nonvideo(regions=regions, encoding: str = coding, exclude_region=None,
get_best_encoding=self.get_best_nonvideo_encoding):
if self.b_frame_flush_timer and exclude_region is None:
# a b-frame is already due, don't clobber it!
exclude_region = vr
quality_pct = 100
if vr:
# give a boost if we have a video region and this is not video:
quality_pct = 140
novideo_options = self.assign_sq_options(options, quality_pct=quality_pct)
self.do_send_regions(damage_time, regions, encoding, novideo_options,
exclude_region=exclude_region, get_best_encoding=get_best_encoding)
if self.is_tray:
sublog("BUG? video for tray - don't use video region!")
send_nonvideo(encoding="")
return
if coding not in ("auto", "stream", "grayscale") and coding not in self.video_encodings:
sublog("not a video encoding: %s", coding)
# keep current encoding selection function
send_nonvideo(get_best_encoding=self.get_best_encoding)
return
if options.get("novideo"):
sublog("video disabled in options")
send_nonvideo(encoding="")
return
if not vr:
sublog("no video region, we may use the video encoder for something else")
self.do_send_regions(damage_time, regions, coding, options)
return
assert not self.full_frames_only
actual_vr = None
if vr in regions:
# found the video region the easy way: exact match in list
actual_vr = vr
else:
# find how many pixels are within the region (roughly):
# find all unique regions that intersect with it:
inter = tuple(x for x in (vr.intersection_rect(r) for r in regions) if x is not None)
if inter:
# merge all regions into one:
in_region = merge_all(inter)
pixels_in_region = vr.width*vr.height
pixels_intersect = in_region.width*in_region.height
if pixels_intersect >= pixels_in_region*40/100:
# we have at least 40% of the video region
# that needs refreshing, do it:
actual_vr = vr
# still no luck?
if actual_vr is None:
# try to find one that has the same dimensions:
same_d = tuple(r for r in regions if r.width == vr.width and r.height == vr.height)
if len(same_d) == 1:
# probably right..
actual_vr = same_d[0]
elif len(same_d) > 1:
# find one that shares at least one coordinate:
same_c = tuple(r for r in same_d if r.x == vr.x or r.y == vr.y)
if len(same_c) == 1:
actual_vr = same_c[0]
if actual_vr is None:
sublog("send_regions: video region %s not found in: %s", vr, regions)
else:
# found the video region:
# sanity check in case the window got resized since:
ww, wh = self.window_dimensions
if actual_vr.x+actual_vr.width > ww or actual_vr.y+actual_vr.height > wh:
sublog("video region partially outside the window")
send_nonvideo(encoding="")
return
# send this using the video encoder:
video_options = self.assign_sq_options(options, quality_pct=70)
# TODO: encode delay can be derived rather than hard-coded
encode_delay = 50
video_options["av-delay"] = max(0, self.get_frame_encode_delay(options) - encode_delay)
self.process_damage_region(damage_time, actual_vr.x, actual_vr.y, actual_vr.width, actual_vr.height,
coding, video_options)
# now subtract this region from the rest:
trimmed = []
for r in regions:
trimmed += r.subtract_rect(actual_vr)
if not trimmed:
sublog("send_regions: nothing left after removing video region %s", actual_vr)
return
sublog("send_regions: subtracted %s from %s gives us %s", actual_vr, regions, trimmed)
regions = trimmed
# merge existing damage delayed region if there is one:
# (this codepath can fire from a video region refresh callback)
dr = self._damage_delayed
if dr:
regions = dr.regions + regions
damage_time = min(damage_time, dr.damage_time)
self._damage_delayed = None
self.cancel_expire_timer()
# decide if we want to send the rest now or delay some more,
# only delay once the video encoder has dealt with a few frames:
event_count = max(0, self.statistics.damage_events_count - self.video_subregion.set_at)
if not actual_vr or event_count < 100:
delay = 0
else:
# non-video is delayed at least 50ms, 4 times the batch delay, but no more than non_max_wait:
elapsed = int(1000.0*(monotonic()-damage_time))
delay = max(self.batch_config.delay*4, self.batch_config.expire_delay)
delay = min(delay, self.video_subregion.non_max_wait-elapsed)
delay = int(delay)
sublog("send_regions event_count=%s, actual_vr=%s, delay=%s",
event_count, actual_vr, delay)
if delay <= 25: