/
window_video_source.py
2063 lines (1888 loc) · 98.9 KB
/
window_video_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) 2013-2018 Antoine Martin <antoine@devloop.org.uk>
# 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
import threading
from math import sqrt
from xpra.net.compression import Compressed, LargeStructure
from xpra.codecs.codec_constants import TransientCodecException, RGB_FORMATS, PIXEL_SUBSAMPLING
from xpra.server.window.window_source import WindowSource, STRICT_MODE, AUTO_REFRESH_SPEED, AUTO_REFRESH_QUALITY, MAX_RGB
from xpra.server.window.region import merge_all #@UnresolvedImport
from xpra.server.window.motion import ScrollData #@UnresolvedImport
from xpra.server.window.video_subregion import VideoSubregion, VIDEO_SUBREGION
from xpra.server.window.video_scoring import get_pipeline_score
from xpra.codecs.codec_constants import PREFERED_ENCODING_ORDER, EDGE_ENCODING_ORDER
from xpra.util import parse_scaling_value, engs, envint, envbool, csv, roundup, print_nested_dict, first_time
from xpra.os_util import monotonic_time, strtobytes, bytestostr, PYTHON3
from xpra.log import Logger
if PYTHON3:
from functools import reduce
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")
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)
VIDEO_TIMEOUT = envint("XPRA_VIDEO_TIMEOUT", 10)
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)
FORCE_AV_DELAY = envint("XPRA_FORCE_AV_DELAY", 0)
B_FRAMES = envbool("XPRA_B_FRAMES", True)
VIDEO_SKIP_EDGE = envbool("XPRA_VIDEO_SKIP_EDGE", False)
SCROLL_ENCODING = envbool("XPRA_SCROLL_ENCODING", True)
SCROLL_MIN_PERCENT = max(1, min(100, envint("XPRA_SCROLL_MIN_PERCENT", 30)))
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
FAST_ORDER = ["jpeg", "rgb32", "rgb24", "png"] + PREFERED_ENCODING_ORDER
class WindowVideoSource(WindowSource):
"""
A WindowSource that handles video codecs.
"""
def __init__(self, *args):
#this will call init_vars():
self.supports_scrolling = False
self.video_subregion = None
WindowSource.__init__(self, *args)
self.supports_eos = self.encoding_options.boolget("eos")
self.scroll_encoding = SCROLL_ENCODING
self.supports_scrolling = self.scroll_encoding and self.encoding_options.boolget("scrolling") and not STRICT_MODE
self.scroll_min_percent = self.encoding_options.intget("scrolling.min-percent", SCROLL_MIN_PERCENT)
self.supports_video_scaling = self.encoding_options.boolget("video_scaling", False)
self.supports_video_b_frames = self.encoding_options.strlistget("video_b_frames", [])
self.video_max_size = self.encoding_options.intlistget("video_max_size", (8192, 8192), 2, 2)
self.video_subregion = VideoSubregion(self.timeout_add, self.source_remove, self.refresh_subregion, self.auto_refresh_delay)
def init_encoders(self):
WindowSource.init_encoders(self)
#for 0.12 onwards: per encoding lists:
self.video_encodings = self.video_helper.get_encodings()
for x in self.video_encodings:
if x in self.server_core_encodings:
self._encoders[x] = self.video_encode
self._encoders["auto"] = 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:
nv_common = (set(self.server_core_encodings) & set(self.core_encodings)) - set(self.video_encodings)
self.non_video_encodings = [x for x in PREFERED_ENCODING_ORDER if x in nv_common]
self.common_video_encodings = [x for x in PREFERED_ENCODING_ORDER if x in self.video_encodings and x in self.core_encodings]
#those two instances should only ever be modified or accessed from the encode thread:
self._csc_encoder = None
self._video_encoder = None
self._last_pipeline_check = 0
def __repr__(self):
return "WindowVideoSource(%s : %s)" % (self.wid, self.window_dimensions)
def init_vars(self):
WindowSource.init_vars(self)
#these constraints get updated with real values
#when we construct the video pipeline:
self.min_w = 1
self.min_h = 1
self.max_w = 16384
self.max_h = 16384
self.width_mask = 0xFFFF
self.height_mask = 0xFFFF
self.actual_scaling = (1, 1)
self.last_pipeline_params = None
self.last_pipeline_scores = ()
self.last_pipeline_time = 0
self.supports_video_scaling = False
self.video_encodings = ()
self.common_video_encodings = ()
self.non_video_encodings = ()
self.edge_encoding = None
self.start_video_frame = 0
self.video_encoder_timer = None
self.b_frame_flush_timer = None
self.b_frame_flush_data = None
self.encode_from_queue_timer = None
self.encode_from_queue_due = 0
self.scroll_data = None
self.last_scroll_time = 0
def do_set_auto_refresh_delay(self, min_delay, delay):
WindowSource.do_set_auto_refresh_delay(self, 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):
self.av_sync_frame_delay = 0
ve = self._video_encoder
if ve:
d = ve.get_info().get("delayed", 0)
self.av_sync_frame_delay += 40 * 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):
i = WindowSource.get_property_info(self)
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):
info = WindowSource.get_info(self)
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["supports_video_scaling"] = self.supports_video_scaling
info["video-max-size"] = self.video_max_size
def addcinfo(prefix, x):
if not x:
return
try:
i = x.get_info()
i[""] = x.get_type()
info[prefix] = i
except:
log.error("Error collecting codec information from %s", x, exc_info=True)
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 or "",
"eos" : self.supports_eos,
})
einfo = {
"pipeline_param" : self.get_pipeline_info(),
"scrolling" : {
"enabled" : self.supports_scrolling,
"min-percent" : self.scroll_min_percent,
}
}
if self._last_pipeline_check>0:
einfo["pipeline_last_check"] = int(1000*(monotonic_time()-self._last_pipeline_check))
lps = self.last_pipeline_scores
if lps:
popts = einfo.setdefault("pipeline_option", {})
for i, lp in enumerate(lps):
popts[i] = self.get_pipeline_score_info(*lp)
info.setdefault("encoding", {}).update(einfo)
return info
def get_pipeline_info(self):
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 get_pipeline_score_info(self, score, scaling, csc_scaling, csc_width, csc_height, csc_spec, enc_in_format, encoder_scaling, enc_width, enc_height, encoder_spec):
def specinfo(x):
try:
return x.codec_type
except:
return repr(x)
pi = {
"score" : score,
"scaling" : scaling,
"format" : str(enc_in_format),
"encoder" : {
"" : specinfo(encoder_spec),
"scaling" : encoder_scaling,
"width" : enc_width,
"height" : enc_height,
},
}
if csc_spec:
pi["csc"] = {
"" : specinfo(csc_spec),
"scaling" : csc_scaling,
"width" : csc_width,
"height" : csc_height,
}
else:
pi["csc"] = "None"
return pi
def suspend(self):
WindowSource.suspend(self)
#we'll create a new video pipeline when resumed:
self.cleanup_codecs()
def cleanup(self):
WindowSource.cleanup(self)
self.cleanup_codecs()
def cleanup_codecs(self):
""" 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):
""" Calls clean() from the encode thread """
csce = self._csc_encoder
ve = self._video_encoder
if csce or ve:
self._csc_encoder = None
self._video_encoder = None
def clean():
self.csc_clean(csce)
self.ve_clean(ve)
self.call_in_encode_thread(False, clean)
def csc_clean(self, csce):
if csce:
csce.clean()
def ve_clean(self, ve):
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.supports_eos and self._video_encoder==ve:
log("sending eos for wid %i", self.wid)
self.queue_packet(("eos", self.wid))
def ui_cleanup(self):
WindowSource.ui_cleanup(self)
self.video_subregion = None
def set_new_encoding(self, encoding, strict=None):
if self.encoding!=encoding:
#ensure we re-init the codecs asap:
self.cleanup_codecs()
WindowSource.set_new_encoding(self, encoding, strict)
def update_encoding_selection(self, encoding=None, exclude=[], init=False):
#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)
for x in self.video_encodings:
if x not in self.core_encodings:
exclude.append(x)
continue
csc_modes = self.full_csc_modes.get(strtobytes(x))
if not csc_modes or x not in self.core_encodings:
exclude.append(x)
if not init:
l = log.warn
else:
l = log
l("client does not support any csc modes with %s", x)
self.common_video_encodings = [x for x in PREFERED_ENCODING_ORDER if x in self.video_encodings and x in self.core_encodings]
log("update_encoding_options: common_video_encodings=%s, csc_encoder=%s, video_encoder=%s", self.common_video_encodings, self._csc_encoder, self._video_encoder)
WindowSource.update_encoding_selection(self, encoding, exclude, init)
def do_set_client_properties(self, properties):
#client may restrict csc modes for specific windows
self.supports_scrolling = self.scroll_encoding and properties.boolget("encoding.scrolling", self.supports_scrolling) and not STRICT_MODE
self.scroll_min_percent = properties.intget("scrolling.min-percent", self.scroll_min_percent)
self.supports_video_scaling = properties.boolget("encoding.video_scaling", self.supports_video_scaling)
self.video_subregion.supported = properties.boolget("encoding.video_subregion", VIDEO_SUBREGION) and VIDEO_SUBREGION
if properties.get("scaling.control") is not None:
self.scaling_control = max(0, min(100, properties.intget("scaling.control", 0)))
WindowSource.do_set_client_properties(self, properties)
#encodings may have changed, so redo this:
nv_common = (set(self.server_core_encodings) & set(self.core_encodings)) - set(self.video_encodings)
self.non_video_encodings = [x for x in PREFERED_ENCODING_ORDER if x in nv_common]
try:
self.edge_encoding = [x for x in EDGE_ENCODING_ORDER if x in self.non_video_encodings][0]
except:
self.edge_encoding = None
log("do_set_client_properties(%s) full_csc_modes=%s, video_scaling=%s, video_subregion=%s, non_video_encodings=%s, edge_encoding=%s, scaling_control=%s",
properties, self.full_csc_modes, self.supports_video_scaling, self.video_subregion.supported, self.non_video_encodings, self.edge_encoding, self.scaling_control)
def get_best_encoding_impl_default(self):
if self.common_video_encodings or self.supports_scrolling:
return self.get_best_encoding_video
return WindowSource.get_best_encoding_impl_default(self)
def get_best_encoding_video(self, ww, wh, speed, quality, current_encoding):
"""
decide whether we send a full window update using the video encoder,
or if a separate small region(s) is a better choice
"""
pixel_count = ww*wh
def nonvideo(q=quality, info=""):
s = max(0, min(100, speed))
q = max(0, min(100, q))
log("nonvideo(%i, %s)", q, info)
return self.get_best_nonvideo_encoding(ww, wh, s, q, self.non_video_encodings[0], self.non_video_encodings)
def lossless(reason):
log("get_best_encoding_video(..) temporarily switching to lossless mode for %8i pixels: %s", pixel_count, reason)
s = max(0, min(100, speed))
q = 100
return self.get_best_nonvideo_encoding(ww, wh, s, q, self.non_video_encodings[0], self.non_video_encodings)
#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")
if self.is_tray:
return nonvideo(100, "system tray")
#ensure the dimensions we use for decision making are the ones actually used:
cww = ww & self.width_mask
cwh = wh & self.height_mask
video_hint = self.content_type=="video"
rgbmax = self._rgb_auto_threshold
videomin = min(640*480, 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)
if pixel_count<=rgbmax or cww<8 or cwh<8:
return lossless("low pixel count")
if current_encoding!="auto" and current_encoding not in self.common_video_encodings:
return nonvideo(info="%s not a supported video encoding" % current_encoding)
if cww*cwh<=MAX_NONVIDEO_PIXELS:
return nonvideo(quality+30, "window is too small")
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_time()
if now-self.statistics.last_resized<0.350:
return nonvideo(quality-30, "resized recently")
if self._current_quality!=quality or self._current_speed!=speed:
return nonvideo(info="quality or speed overriden")
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 graphics
return nonvideo(quality+30, "not the video region")
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*videomin:
return nonvideo(quality+30, "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(quality+30, "framerate lowered")
#calculate the threshold for using video vs small regions:
factors = (max(1, (speed-75)/5.0), #speed multiplier
1 + int(self.is_OR or self.is_tray)*2, #OR windows tend to be static
max(1, 10-self._sequence), #gradual discount the first 9 frames, as the window may be temporary
1.0 / (int(bool(self._video_encoder)) + 1), #if we have a video encoder already, make it more likely we'll use it:
(1-video_hint/2.0), #video hint lowers the threshold
)
max_nvp = int(reduce(operator.mul, factors, MAX_NONVIDEO_PIXELS))
if pixel_count<=max_nvp:
#below threshold
return nonvideo(quality+30, "not enough pixels")
if cww<self.min_w or cww>self.max_w or cwh<self.min_h or cwh>self.max_h:
#failsafe:
return nonvideo(info="size out of range")
return current_encoding
def get_best_nonvideo_encoding(self, ww, wh, speed, quality, current_encoding=None, options=[]):
#if we're here, then the window has no alpha (or the client cannot handle alpha)
#and we can ignore the current encoding
options = options or self.non_video_encodings
depth = self.image_depth
if depth==8 and "png/P" in options:
return "png/P"
pixel_count = ww*wh
if pixel_count<self._rgb_auto_threshold or self.is_tray or ww<=2 or wh<=2:
#high speed and high quality, rgb is still good
if "rgb24" in options:
return "rgb24"
if "rgb32" in options:
return "rgb32"
#use sliding scale for lossless threshold
#(high speed favours switching to lossy sooner)
#take into account how many pixels need to be encoded:
#more pixels means we switch to lossless more easily
lossless_q = min(100, self._lossless_threshold_base + self._lossless_threshold_pixel_boost * pixel_count / (ww*wh))
if quality<lossless_q and depth>16 and "jpeg" in options and ww>=8 and wh>=8:
#assume that we have "turbojpeg",
#which beats everything in terms of efficiency for lossy compression:
return "jpeg"
if "webp" in options and pixel_count>=16384 and ww>=2 and wh>=2 and depth in (24, 32):
return "webp"
#lossless options:
if speed==100 or (speed>=95 and pixel_count<MAX_RGB) or depth>24:
if depth>24 and "rgb32" in options:
return "rgb32"
if "rgb24" in options:
return "rgb24"
if "rgb32" in options:
return "rgb32"
if "png" in options:
return "png"
if "jpeg2000" in options and ww>=32 and wh>=32 and depth in (24, 32):
return "jpeg2000"
#we failed to find a good match, default to the first of the options..
if options:
return options[0]
return None #can happen during cleanup!
def do_damage(self, ww, wh, x, y, w, h, options):
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()
WindowSource.do_damage(self, ww, wh, x, y, w, h, options)
def cancel_damage(self):
self.cancel_encode_from_queue()
self.free_encode_queue_images()
self.video_subregion.cancel_refresh_timer()
self.scroll_data = None
self.last_scroll_time = 0
WindowSource.cancel_damage(self)
#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={}):
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.scroll_data = None
self.last_scroll_time = 0
if self.non_video_encodings:
#refresh the whole window in one go:
damage_options["novideo"] = True
WindowSource.full_quality_refresh(self, damage_options)
def must_batch(self, delay):
#force batching when using video region
#because the video region code is in the send_delayed path
return self.video_subregion.rectangle is not None or WindowSource.must_batch(self, delay)
def get_speed(self, encoding):
s = WindowSource.get_speed(self, encoding)
#give a boost if we have a video region and this is not video:
if self.video_subregion.rectangle and encoding not in self.video_encodings:
s += 25
return min(100, s)
def get_quality(self, encoding):
q = WindowSource.get_quality(self, encoding)
#give a boost if we have a video region and this is not video:
if self.video_subregion.rectangle and encoding not in self.video_encodings:
q += 40
return min(100, q)
def client_decode_error(self, error, message):
#maybe the stream is now corrupted..
self.cleanup_codecs()
WindowSource.client_decode_error(self, error, message)
def timer_full_refresh(self):
self.flush_video_encoder_now()
WindowSource.timer_full_refresh(self)
def get_refresh_exclude(self):
#exclude video region (if any) from lossless refresh:
return self.video_subregion.rectangle
def refresh_subregion(self, regions):
#callback from video subregion to trigger a refresh of some areas
regionrefreshlog("refresh_subregion(%s)", regions)
if not regions or not self.can_refresh():
return False
now = monotonic_time()
if now-self.global_statistics.last_congestion_time<5:
return False
self.flush_video_encoder_now()
encoding = self.auto_refresh_encodings[0]
options = self.get_refresh_options()
WindowSource.do_send_delayed_regions(self, now, regions, encoding, options, get_best_encoding=self.get_refresh_subregion_encoding)
return True
def get_refresh_subregion_encoding(self, *_args):
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
return self.get_best_nonvideo_encoding(w, h, AUTO_REFRESH_SPEED, AUTO_REFRESH_QUALITY, self.auto_refresh_encodings[0], self.auto_refresh_encodings)
def remove_refresh_region(self, region):
#override so we can update the subregion timers / regions tracking:
WindowSource.remove_refresh_region(self, region)
self.video_subregion.remove_refresh_region(region)
def add_refresh_region(self, region):
#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
vr = self.video_subregion.rectangle
if vr is None:
#no video region, normal code path:
return WindowSource.add_refresh_region(self, 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 WindowSource.add_refresh_region(self, 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)
pixels_modified = 0
for r in region.substract_rect(vr):
pixels_modified += WindowSource.add_refresh_region(self, r)
return pixels_modified
def matches_video_subregion(self, width, height):
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):
vr = self.video_subregion.rectangle
if not vr:
return False
events_count = self.statistics.damage_events_count - self.video_subregion.set_at
min_video_events = MIN_VIDEO_EVENTS
min_video_fps = MIN_VIDEO_FPS
if self.content_type=="video":
min_video_events //= 2
min_video_fps //= 2
if events_count<min_video_events:
return False
if self.video_subregion.fps<min_video_fps:
return False
return True
def do_send_delayed_regions(self, damage_time, regions, coding, options):
"""
Overriden here so 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=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
WindowSource.do_send_delayed_regions(self, damage_time, regions, encoding, 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!")
return send_nonvideo(encoding=None)
if coding!="auto" and coding not in self.video_encodings:
sublog("not a video encoding: %s" % coding)
#keep current encoding selection function
return send_nonvideo(get_best_encoding=self.get_best_encoding)
if options.get("novideo"):
sublog("video disabled in options")
return send_nonvideo(encoding=None)
if not vr:
sublog("no video region, we may use the video encoder for something else")
WindowSource.do_send_delayed_regions(self, 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 = [x for x in (vr.intersection_rect(r) for r in regions) if x is not None]
if len(inter)>0:
#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 = [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 = [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_delayed_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.get_dimensions()
if actual_vr.x+actual_vr.width>ww or actual_vr.y+actual_vr.height>wh:
sublog("video region partially outside the window")
return send_nonvideo(encoding=None)
#send this using the video encoder:
video_options = options.copy()
video_options["av-sync"] = True
self.process_damage_region(damage_time, actual_vr.x, actual_vr.y, actual_vr.width, actual_vr.height, coding, video_options, 0)
#now substract this region from the rest:
trimmed = []
for r in regions:
trimmed += r.substract_rect(actual_vr)
if not trimmed:
sublog("send_delayed_regions: nothing left after removing video region %s", actual_vr)
return
sublog("send_delayed_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[1] + regions
damage_time = min(damage_time, dr[0])
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 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_time()-damage_time))
delay = max(self.batch_config.delay*4, 50)
delay = min(delay, self.video_subregion.non_max_wait-elapsed)
if delay<=25:
send_nonvideo(regions=regions, encoding=None, exclude_region=actual_vr)
else:
self._damage_delayed = damage_time, regions, coding, options or {}
sublog("send_delayed_regions: delaying non video regions %s some more by %ims", regions, delay)
self.expire_timer = self.timeout_add(int(delay), self.expire_delayed_region, delay)
def must_encode_full_frame(self, encoding):
return self.full_frames_only or (encoding in self.video_encodings) or not self.non_video_encodings
def process_damage_region(self, damage_time, x, y, w, h, coding, options, flush=0):
"""
Called by 'damage' or 'send_delayed_regions' to process a damage region.
Actual damage region processing:
we extract the rgb data from the pixmap and:
* if doing av-sync, we place the data on the encode queue with a timer,
when the timer fires, we queue the work for the damage thread
* without av-sync, we just queue the work immediately
The damage thread will call make_data_packet_cb which does the actual compression.
This runs in the UI thread.
"""
assert self.ui_thread == threading.current_thread()
assert coding is not None
if w==0 or h==0:
return
if not self.window.is_managed():
log("the window %s is not composited!?", self.window)
return
self._sequence += 1
sequence = self._sequence
if self.is_cancelled(sequence):
log("get_window_pixmap: dropping damage request with sequence=%s", sequence)
return
rgb_request_time = monotonic_time()
image = self.window.get_image(x, y, w, h)
if image is None:
log("get_window_pixmap: no pixel data for window %s, wid=%s", self.window, self.wid)
return
if self.is_cancelled(sequence):
image.free()
return
self.pixel_format = image.get_pixel_format()
self.image_depth = image.get_depth()
#image may have been clipped to the new window size during resize:
w = image.get_width()
h = image.get_height()
av_delay = self.get_frame_encode_delay(options)
#TODO: encode delay can be derived rather than hard-coded
encode_delay = 50
av_delay = max(0, av_delay - encode_delay)
#freeze if:
# * we want av-sync
# * the video encoder needs a thread safe image
# (the xshm backing may change from underneath us if we don't freeze it)
must_freeze = av_delay>0 or ((coding in self.video_encodings or coding=="auto") and not image.is_thread_safe())
if must_freeze:
image.freeze()
def call_encode(ew, eh, eimage, encoding, eflush):
self._sequence += 1
sequence = self._sequence
if self.is_cancelled(sequence):
log("get_window_pixmap: dropping damage request with sequence=%s", sequence)
return
now = monotonic_time()
log("process_damage_region: wid=%i, adding pixel data to encode queue (%4ix%-4i - %5s), elapsed time: %.1f ms, request time: %.1f ms, frame delay=%ims",
self.wid, ew, eh, encoding, 1000*(now-damage_time), 1000*(now-rgb_request_time), av_delay)
item = (ew, eh, damage_time, now, eimage, encoding, sequence, options, eflush)
if av_delay<0:
self.call_in_encode_thread(True, self.make_data_packet_cb, *item)
else:
self.encode_queue.append(item)
self.schedule_encode_from_queue(av_delay)
#now figure out if we need to send edges separately:
if coding in self.video_encodings and self.edge_encoding and not VIDEO_SKIP_EDGE:
dw = w - (w & self.width_mask)
dh = h - (h & self.height_mask)
if dw>0:
sub = image.get_sub_image(w-dw, 0, dw, h)
call_encode(dw, h, sub, self.edge_encoding, flush+1+int(dh>0))
w = w & self.width_mask
if dh>0:
sub = image.get_sub_image(0, h-dh, w, dh)
call_encode(dw, h, sub, self.edge_encoding, flush+1)
h = h & self.height_mask
#the main area:
call_encode(w, h, image, coding, flush)
def get_frame_encode_delay(self, options):
if FORCE_AV_DELAY>0:
return FORCE_AV_DELAY
if options.get("av-sync", False):
return -1
l = len(self.encode_queue)
if l>=self.encode_queue_max_size:
#we must free some space!
return 0
return self.av_sync_delay
def cancel_encode_from_queue(self):
#free all items in the encode queue:
eqt = self.encode_from_queue_timer
avsynclog("cancel_encode_from_queue() timer=%s for wid=%i", eqt, self.wid)
if eqt:
self.encode_from_queue_timer = None
self.source_remove(eqt)
def free_encode_queue_images(self):
eq = self.encode_queue
avsynclog("free_encode_queue_images() freeing %i images for wid=%i", len(eq), self.wid)
if not eq:
return
self.encode_queue = []
for item in eq:
try:
self.free_image_wrapper(item[4])
except:
log.error("Error: cannot free image wrapper %s", item[4], exc_info=True)
def schedule_encode_from_queue(self, av_delay):
#must be called from the UI thread for synchronization
#we ensure that the timer will fire no later than av_delay
#re-scheduling it if it was due later than that
due = monotonic_time()+av_delay
if self.encode_from_queue_due==0 or due<self.encode_from_queue_due:
self.encode_from_queue_due = due
self.cancel_encode_from_queue()
self.encode_from_queue_timer = self.timeout_add(av_delay, self.timer_encode_from_queue)
def timer_encode_from_queue(self):
self.encode_from_queue_timer = None
self.encode_from_queue_due = 0
self.call_in_encode_thread(True, self.encode_from_queue)
def encode_from_queue(self):
#note: we use a queue here to ensure we preserve the order
#(so we encode frames in the same order they were grabbed)
eq = self.encode_queue
avsynclog("encode_from_queue: %s items for wid=%i", len(eq), self.wid)
if not eq:
return #nothing to encode, must have been picked off already
self.update_av_sync_delay()
#find the first item which is due
#in seconds, same as monotonic_time():
if len(self.encode_queue)>=self.encode_queue_max_size:
av_delay = 0 #we must free some space!
elif FORCE_AV_DELAY>0:
av_delay = FORCE_AV_DELAY/1000.0
else:
av_delay = self.av_sync_delay/1000.0
now = monotonic_time()
still_due = []
remove = []
index = 0
item = None
sequence = None
done_packet = False #only one packet per iteration
try:
for index,item in enumerate(eq):
#item = (w, h, damage_time, now, image, coding, sequence, options, flush)
sequence = item[6]
if self.is_cancelled(sequence):
self.free_image_wrapper(item[4])
remove.append(index)
continue
ts = item[3]
due = ts + av_delay
if due<=now and not done_packet:
#found an item which is due
remove.append(index)
avsynclog("encode_from_queue: processing item %s/%s (overdue by %ims)", index+1, len(self.encode_queue), int(1000*(now-due)))
self.make_data_packet_cb(*item)
done_packet = True
else:
#we only process only one item per call (see "done_packet")
#and just keep track of extra ones:
still_due.append(int(1000*(due-now)))
except Exception:
if not self.is_cancelled(sequence):
avsynclog.error("error processing encode queue at index %i", index)
avsynclog.error("item=%s", item, exc_info=True)
#remove the items we've dealt with:
#(in reverse order since we pop them from the queue)
if remove:
for x in reversed(remove):
eq.pop(x)
#if there are still some items left in the queue, re-schedule:
if len(still_due)==0:
avsynclog("encode_from_queue: nothing due")
return
first_due = max(0, min(still_due))
avsynclog("encode_from_queue: first due in %ims, due list=%s (av-sync delay=%i, actual=%i, for wid=%i)", first_due, still_due, self.av_sync_delay, av_delay, self.wid)
self.idle_add(self.schedule_encode_from_queue, first_due)
def update_encoding_options(self, force_reload=False):
"""
This is called when we want to force a full re-init (force_reload=True)
or from the timer that allows to tune the quality and speed.
(this tuning is done in WindowSource.reconfigure)
Here we re-evaluate if the pipeline we are currently using
is really the best one, and if not we invalidate it.
This uses get_video_pipeline_options() to get a list of pipeline
options with a score for each.
Can be called from any thread.
"""
WindowSource.update_encoding_options(self, force_reload)
vs = self.video_subregion
if vs:
if (self.encoding!="auto" and self.encoding not in self.common_video_encodings) or \
self.full_frames_only or STRICT_MODE or not self.non_video_encodings or not self.common_video_encodings or \
(self._mmap and self._mmap_size>0):
#cannot use video subregions
#FIXME: small race if a refresh timer is due when we change encoding - meh
vs.reset()
else:
old = vs.rectangle
ww, wh = self.window_dimensions
vs.identify_video_subregion(ww, wh, self.statistics.damage_events_count, self.statistics.last_damage_events, self.statistics.last_resized)
newrect = vs.rectangle
if newrect is None or old is None or newrect!=old:
self.cleanup_codecs()
if newrect:
#when we have a video region, lower the lossless threshold
#especially for small regions
self._lossless_threshold_base = min(80, 10+self._current_speed//5)
self._lossless_threshold_pixel_boost = 90-self._current_speed//5
#remove this from regular refresh:
if old is None or old!=newrect:
refreshlog("identified new video region: %s", newrect)
#figure out if the new region had pending regular refreshes:
subregion_needs_refresh = any(newrect.intersects_rect(x) for x in self.refresh_regions)
if old:
#we don't bother substracting new and old (too complicated)
refreshlog("scheduling refresh of old region: %s", old)
#this may also schedule a refresh:
WindowSource.add_refresh_region(self, old)
WindowSource.remove_refresh_region(self, newrect)
if not self.refresh_regions:
self.cancel_refresh_timer()
if subregion_needs_refresh:
vs.add_video_refresh(newrect)
else:
refreshlog("video region unchanged: %s - no change in refresh", newrect)
elif old:
#add old region to regular refresh:
refreshlog("video region cleared, scheduling refresh of old region: %s", old)
self.add_refresh_region(old)