-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
gstwebrtc_app.py
1782 lines (1536 loc) · 92.4 KB
/
gstwebrtc_app.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 Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# This file incorporates work covered by the following copyright and
# permission notice:
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import base64
import json
import logging
import os
import re
import sys
import time
logger = logging.getLogger("gstwebrtc_app")
logger.setLevel(logging.INFO)
try:
import gi
gi.require_version('GLib', "2.0")
gi.require_version('Gst', "1.0")
gi.require_version('GstRtp', "1.0")
gi.require_version('GstSdp', "1.0")
gi.require_version('GstWebRTC', "1.0")
from gi.repository import GLib, Gst, GstRtp, GstSdp, GstWebRTC
fract = Gst.Fraction(60, 1)
del fract
except Exception as e:
msg = """ERROR: could not find working GStreamer-Python installation.
If GStreamer is installed at a certain location, set the path to the environment variable GSTREAMER_PATH, then make sure your environment is set correctly using the below commands (for Debian-like distributions):
export GSTREAMER_PATH="${GSTREAMER_PATH:-$(pwd)}"
export PATH="${GSTREAMER_PATH}/bin${PATH:+:${PATH}}"
export LD_LIBRARY_PATH="${GSTREAMER_PATH}/lib/x86_64-linux-gnu${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
export GST_PLUGIN_PATH="${GSTREAMER_PATH}/lib/x86_64-linux-gnu/gstreamer-1.0${GST_PLUGIN_PATH:+:${GST_PLUGIN_PATH}}"
export GST_PLUGIN_SYSTEM_PATH="${XDG_DATA_HOME:-${HOME:-~}/.local/share}/gstreamer-1.0/plugins:/usr/lib/x86_64-linux-gnu/gstreamer-1.0${GST_PLUGIN_SYSTEM_PATH:+:${GST_PLUGIN_SYSTEM_PATH}}"
export GI_TYPELIB_PATH="${GSTREAMER_PATH}/lib/x86_64-linux-gnu/girepository-1.0:/usr/lib/x86_64-linux-gnu/girepository-1.0${GI_TYPELIB_PATH:+:${GI_TYPELIB_PATH}}"
export PYTHONPATH="${GSTREAMER_PATH}/lib/python3/dist-packages${PYTHONPATH:+:${PYTHONPATH}}"
Replace "x86_64-linux-gnu" in other architectures manually or use "$(gcc -print-multiarch)" in place.
"""
logger.error(msg)
logger.error(e)
sys.exit(1)
logger.info("GStreamer-Python install looks OK")
class GSTWebRTCAppError(Exception):
pass
class GSTWebRTCApp:
def __init__(self, stun_servers=None, turn_servers=None, audio_channels=2, framerate=30, encoder=None, gpu_id=0, video_bitrate=2000, audio_bitrate=96000, keyframe_distance=-1.0, congestion_control=False, video_packetloss_percent=0.0, audio_packetloss_percent=0.0):
"""Initialize GStreamer WebRTC app.
Initializes GObjects and checks for required plugins.
Arguments:
stun_servers {[list of string]} -- Optional STUN server uris in the form of:
stun:<host>:<port>
turn_servers {[list of strings]} -- Optional TURN server uris in the form of:
turn://<user>:<password>@<host>:<port>
"""
self.stun_servers = stun_servers
self.turn_servers = turn_servers
self.audio_channels = audio_channels
self.pipeline = None
self.webrtcbin = None
self.data_channel = None
self.rtpgccbwe = None
self.congestion_control = congestion_control
self.encoder = encoder
self.gpu_id = gpu_id
self.framerate = framerate
self.video_bitrate = video_bitrate
self.audio_bitrate = audio_bitrate
# Keyframe distance in seconds
self.keyframe_distance = keyframe_distance
# Enforce minimum keyframe interval to 60 frames
self.min_keyframe_frame_distance = 60
self.keyframe_frame_distance = -1 if self.keyframe_distance == -1.0 else max(self.min_keyframe_frame_distance, int(self.framerate * self.keyframe_distance))
# Set VBV/HRD buffer multiplier to frame time, set 1.5x when optimal (no keyframes/GOP) to prevent quality degradation in encoders, relax 2x when keyframe/GOP is periodic
self.vbv_multiplier_nv = 1.5 if self.keyframe_distance == -1.0 else 3
self.vbv_multiplier_va = 1.5 if self.keyframe_distance == -1.0 else 3
self.vbv_multiplier_vp = 1.5 if self.keyframe_distance == -1.0 else 3
self.vbv_multiplier_sw = 1.5 if self.keyframe_distance == -1.0 else 3
# Packet loss base percentage
self.video_packetloss_percent = video_packetloss_percent
self.audio_packetloss_percent = audio_packetloss_percent
# Prevent bitrate from overshooting because of FEC
self.fec_video_bitrate = int(self.video_bitrate / (1.0 + (self.video_packetloss_percent / 100.0)))
# Keep audio bitrate to exact value and increase effective bitrate after FEC to prevent audio quality degradation
self.fec_audio_bitrate = int(self.audio_bitrate * (1.0 + (self.audio_packetloss_percent / 100.0)))
# WebRTC ICE and SDP events
self.on_ice = lambda mlineindex, candidate: logger.warn(
'unhandled ice event')
self.on_sdp = lambda sdp_type, sdp: logger.warn('unhandled sdp event')
# Data channel events
self.on_data_open = lambda: logger.warn('unhandled on_data_open')
self.on_data_close = lambda: logger.warn('unhandled on_data_close')
self.on_data_error = lambda: logger.warn('unhandled on_data_error')
self.on_data_message = lambda msg: logger.warn(
'unhandled on_data_message')
Gst.init(None)
self.check_plugins()
self.ximagesrc = None
self.ximagesrc_caps = None
self.last_cursor_sent = None
def stop_ximagesrc(self):
"""Helper function to stop the ximagesrc, useful when resizing
"""
if self.ximagesrc:
self.ximagesrc.set_state(Gst.State.NULL)
def start_ximagesrc(self):
"""Helper function to start the ximagesrc, useful when resizing
"""
if self.ximagesrc:
self.ximagesrc.set_property("endx", 0)
self.ximagesrc.set_property("endy", 0)
self.ximagesrc.set_state(Gst.State.PLAYING)
# [START build_webrtcbin_pipeline]
def build_webrtcbin_pipeline(self, audio_only=False):
"""Adds the webrtcbin elements to the pipeline.
The video and audio pipelines are linked to this in the
build_video_pipeline() and build_audio_pipeline() methods.
"""
# Reference configuration for webrtcbin including congestion control:
# https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/blob/main/net/webrtc/src/webrtcsink/imp.rs
# Create webrtcbin element named app
self.webrtcbin = Gst.ElementFactory.make("webrtcbin", "app")
# The bundle policy affects how the SDP is generated.
# This will ultimately determine how many tracks the browser receives.
# Setting this to max-compat will prioritize separate tracks for
# audio and video.
# See also: https://webrtcstandards.info/sdp-bundle/
self.webrtcbin.set_property("bundle-policy", "max-compat")
# Set default jitterbuffer latency to the minimum possible
self.webrtcbin.set_property("latency", 0)
# Connect signal handlers
if self.congestion_control and not audio_only:
self.webrtcbin.connect(
'request-aux-sender', lambda webrtcbin, dtls_transport: self.__request_aux_sender_gcc(webrtcbin, dtls_transport))
self.webrtcbin.connect(
'on-negotiation-needed', lambda webrtcbin: self.__on_negotiation_needed(webrtcbin))
self.webrtcbin.connect('on-ice-candidate', lambda webrtcbin, mlineindex,
candidate: self.__send_ice(webrtcbin, mlineindex, candidate))
# Add STUN server
# TODO: figure out how to add more than one STUN server.
if self.stun_servers:
logger.info("updating STUN server")
self.webrtcbin.set_property("stun-server", self.stun_servers[0])
# Add TURN server
if self.turn_servers:
for i, turn_server in enumerate(self.turn_servers):
logger.info("updating TURN server")
if i == 0:
self.webrtcbin.set_property("turn-server", turn_server)
else:
self.webrtcbin.emit("add-turn-server", turn_server)
# Add element to the pipeline.
self.pipeline.add(self.webrtcbin)
# [END build_webrtcbin_pipeline]
# [START build_video_pipeline]
def build_video_pipeline(self):
"""Adds the RTP video stream to the pipeline.
"""
# Create ximagesrc element named x11
# Note that when using the ximagesrc plugin, ensure that the X11 server was
# started with shared memory support: '+extension MIT-SHM' to achieve
# full frame rates.
# You can check if XSHM is in use with the following command:
# GST_DEBUG=default:5 gst-launch-1.0 ximagesrc ! fakesink num-buffers=1 2>&1 |grep -i xshm
self.ximagesrc = Gst.ElementFactory.make("ximagesrc", "x11")
ximagesrc = self.ximagesrc
# disables display of the pointer using the XFixes extension,
# common when building a remote desktop interface as the clients
# mouse pointer can be used to give the user perceived lower latency.
# This can be programmatically toggled after the pipeline is started
# for example if the user is viewing fullscreen in the browser,
# they may want to revert to seeing the remote cursor when the
# client side cursor disappears.
ximagesrc.set_property("show-pointer", 0)
# Tells GStreamer that you are using an X11 window manager or
# compositor with off-screen buffer. If you are not using a
# window manager this can be set to 0. It's also important to
# make sure that your X11 server is running with the XSHM extension
# to ensure direct memory access to frames which will reduce latency.
ximagesrc.set_property("remote", 1)
# Defines the size in bytes to read per buffer. Increasing this from
# the default of 4096 bytes helps performance when capturing high
# resolutions like 1080P, and 2K.
ximagesrc.set_property("blocksize", 16384)
# The X11 XDamage extension allows the X server to indicate when a
# regions of the screen has changed. While this can significantly
# reduce CPU usage when the screen is idle, it has little effect with
# constant motion. This can also have a negative consequences with H.264
# as the video stream can drop out and take several seconds to recover
# until a valid I-Frame is received.
# Set this to 0 for most streaming use cases.
ximagesrc.set_property("use-damage", 0)
# Create capabilities for ximagesrc
self.ximagesrc_caps = Gst.caps_from_string("video/x-raw")
# Setting the framerate=60/1 capability instructs the ximagesrc element
# to generate buffers at 60 frames per second (FPS).
# The higher the FPS, the lower the latency so this parameter is one
# way to set the overall target latency of the pipeline though keep in
# mind that the pipeline may not always perform at the full 60 FPS.
self.ximagesrc_caps.set_value("framerate", Gst.Fraction(self.framerate, 1))
# Create a capability filter for the ximagesrc_caps
self.ximagesrc_capsfilter = Gst.ElementFactory.make("capsfilter")
self.ximagesrc_capsfilter.set_property("caps", self.ximagesrc_caps)
# ADD_ENCODER: Add new encoder to this list and modify all locations with "ADD_ENCODER:"
# Reference configuration for fixing when something is broken in web browsers:
# https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/blob/main/net/webrtc/src/webrtcsink/imp.rs
if self.encoder in ["nvh264enc"]:
# Upload buffers from ximagesrc directly to CUDA memory where
# the colorspace conversion will be performed.
cudaupload = Gst.ElementFactory.make("cudaupload")
if self.gpu_id >= 0:
cudaupload.set_property("cuda-device-id", self.gpu_id)
# Convert the colorspace from BGRx to NVENC compatible format.
# This is performed with CUDA which reduces the overall CPU load
# compared to using the software videoconvert element.
cudaconvert = Gst.ElementFactory.make("cudaconvert")
if self.gpu_id >= 0:
cudaconvert.set_property("cuda-device-id", self.gpu_id)
# Instructs cudaconvert to handle Quality of Service (QOS) events
# from the rest of the pipeline. Setting this value increases
# encoder stability.
cudaconvert.set_property("qos", True)
# Convert ximagesrc BGRx format to NV12 using cudaconvert.
# This is a more compatible format for client-side software decoders.
cudaconvert_caps = Gst.caps_from_string("video/x-raw(memory:CUDAMemory)")
cudaconvert_caps.set_value("format", "NV12")
cudaconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
cudaconvert_capsfilter.set_property("caps", cudaconvert_caps)
# Create the nvh264enc element named nvenc.
# This is the heart of the video pipeline that converts the raw
# frame buffers to an H.264 encoded byte-stream on the GPU.
if self.gpu_id > 0:
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvh264enc = Gst.ElementFactory.make("nvcudah264device{}enc".format(self.gpu_id), "nvenc")
else:
nvh264enc = Gst.ElementFactory.make("nvh264device{}enc".format(self.gpu_id), "nvenc")
else:
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvh264enc = Gst.ElementFactory.make("nvcudah264enc", "nvenc")
else:
nvh264enc = Gst.ElementFactory.make("nvh264enc", "nvenc")
# The initial bitrate of the encoder in bits per second.
# Setting this to 0 will use the bitrate from the NVENC preset.
# This parameter can be set while the pipeline is running using the
# set_video_bitrate() method. This helps to match the available
# bandwidth. If set too high, the cliend side jitter buffer will
# not be unable to lock on to the stream and it will fail to render.
nvh264enc.set_property("bitrate", self.fec_video_bitrate)
# Rate control mode tells the encoder how to compress the frames to
# reach the target bitrate. A Constant Bit Rate (CBR) setting is best
# for streaming use cases as bitrate is the most important factor.
# A Variable Bit Rate (VBR) setting tells the encoder to adjust the
# compression level based on scene complexity, something not needed
# when streaming in real-time.
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvh264enc.set_property("rate-control", "cbr")
else:
nvh264enc.set_property("rc-mode", "cbr")
# Group of Pictures (GOP) size is the distance between I-Frames that
# contain the full frame data needed to render a whole frame.
# A negative consequence when using infinite GOP size is that
# when packets are lost, the decoder may never recover.
# NVENC supports infinite GOP by setting this to -1.
nvh264enc.set_property("gop-size", -1 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
# Minimize GOP-to-GOP rate fluctuations
nvh264enc.set_property("strict-gop", True)
# The NVENC encoder supports a limited number of encoding presets.
# These presets are different than the open x264 standard.
# The presets control the picture coding technique, bitrate,
# and encoding quality.
#
# See this link for details on NVENC parameters recommended for
# low-latency streaming (also a setting reference for other encoders):
# https://docs.nvidia.com/video-technologies/video-codec-sdk/12.2/nvenc-video-encoder-api-prog-guide/index.html#recommended-nvenc-settings
#
# See this link for details on each preset:
# https://docs.nvidia.com/video-technologies/video-codec-sdk/12.2/nvenc-preset-migration-guide/index.html
nvh264enc.set_property("aud", False)
# Do not automatically add b-frames
nvh264enc.set_property("b-adapt", False)
# Disable lookahead
nvh264enc.set_property("rc-lookahead", 0)
# Set VBV/HRD buffer size (kbits) to optimize for live streaming
nvh264enc.set_property("vbv-buffer-size", int((self.fec_video_bitrate + self.framerate - 1) // self.framerate * self.vbv_multiplier_nv))
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvh264enc.set_property("b-frames", 0)
# Zero-latency operation mode (no reordering delay)
nvh264enc.set_property("zero-reorder-delay", True)
else:
nvh264enc.set_property("bframes", 0)
# Zero-latency operation mode (no reordering delay)
nvh264enc.set_property("zerolatency", True)
if Gst.version().major == 1 and Gst.version().minor > 20:
# CABAC is more bandwidth-efficient compared to CAVLC at a tradeoff of slight increase (<= 1 ms) in decoding time
nvh264enc.set_property("cabac", True)
# Insert sequence headers (SPS/PPS) per IDR
nvh264enc.set_property("repeat-sequence-header", True)
if Gst.version().major == 1 and Gst.version().minor > 22:
nvh264enc.set_property("preset", "p4")
nvh264enc.set_property("tune", "ultra-low-latency")
# Two-pass mode allows to detect more motion vectors,
# better distribute bitrate across the frame
# and more strictly adhere to bitrate limits.
nvh264enc.set_property("multi-pass", "two-pass-quarter")
else:
nvh264enc.set_property("preset", "low-latency-hq")
elif self.encoder in ["nvh265enc"]:
cudaupload = Gst.ElementFactory.make("cudaupload")
if self.gpu_id >= 0:
cudaupload.set_property("cuda-device-id", self.gpu_id)
cudaconvert = Gst.ElementFactory.make("cudaconvert")
if self.gpu_id >= 0:
cudaconvert.set_property("cuda-device-id", self.gpu_id)
cudaconvert.set_property("qos", True)
cudaconvert_caps = Gst.caps_from_string("video/x-raw(memory:CUDAMemory)")
cudaconvert_caps.set_value("format", "NV12")
cudaconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
cudaconvert_capsfilter.set_property("caps", cudaconvert_caps)
if self.gpu_id > 0:
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvh265enc = Gst.ElementFactory.make("nvcudah265device{}enc".format(self.gpu_id), "nvenc")
else:
nvh265enc = Gst.ElementFactory.make("nvh265device{}enc".format(self.gpu_id), "nvenc")
else:
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvh265enc = Gst.ElementFactory.make("nvcudah265enc", "nvenc")
else:
nvh265enc = Gst.ElementFactory.make("nvh265enc", "nvenc")
nvh265enc.set_property("bitrate", self.fec_video_bitrate)
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvh265enc.set_property("rate-control", "cbr")
else:
nvh265enc.set_property("rc-mode", "cbr")
nvh265enc.set_property("gop-size", -1 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
nvh265enc.set_property("strict-gop", True)
nvh265enc.set_property("aud", False)
# B-frames in H.265 are only provided with newer GPUs
nvenc_properties = [nvenc_property.name for nvenc_property in nvh265enc.list_properties()]
if "b-adapt" in nvenc_properties:
nvh265enc.set_property("b-adapt", False)
nvh265enc.set_property("rc-lookahead", 0)
nvh265enc.set_property("vbv-buffer-size", int((self.fec_video_bitrate + self.framerate - 1) // self.framerate * self.vbv_multiplier_nv))
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
if "b-frames" in nvenc_properties:
nvh265enc.set_property("b-frames", 0)
nvh265enc.set_property("zero-reorder-delay", True)
else:
if "bframes" in nvenc_properties:
nvh265enc.set_property("bframes", 0)
nvh265enc.set_property("zerolatency", True)
if Gst.version().major == 1 and Gst.version().minor > 20:
nvh265enc.set_property("repeat-sequence-header", True)
if Gst.version().major == 1 and Gst.version().minor > 22:
nvh265enc.set_property("preset", "p4")
nvh265enc.set_property("tune", "ultra-low-latency")
nvh265enc.set_property("multi-pass", "two-pass-quarter")
else:
nvh265enc.set_property("preset", "low-latency-hq")
elif self.encoder in ["nvav1enc"]:
cudaupload = Gst.ElementFactory.make("cudaupload")
if self.gpu_id >= 0:
cudaupload.set_property("cuda-device-id", self.gpu_id)
cudaconvert = Gst.ElementFactory.make("cudaconvert")
if self.gpu_id >= 0:
cudaconvert.set_property("cuda-device-id", self.gpu_id)
cudaconvert.set_property("qos", True)
cudaconvert_caps = Gst.caps_from_string("video/x-raw(memory:CUDAMemory)")
cudaconvert_caps.set_value("format", "NV12")
cudaconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
cudaconvert_capsfilter.set_property("caps", cudaconvert_caps)
if self.gpu_id > 0:
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvav1enc = Gst.ElementFactory.make("nvcudaav1device{}enc".format(self.gpu_id), "nvenc")
else:
nvav1enc = Gst.ElementFactory.make("nvav1device{}enc".format(self.gpu_id), "nvenc")
else:
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvav1enc = Gst.ElementFactory.make("nvcudaav1enc", "nvenc")
else:
nvav1enc = Gst.ElementFactory.make("nvav1enc", "nvenc")
nvav1enc.set_property("bitrate", self.fec_video_bitrate)
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvav1enc.set_property("rate-control", "cbr")
else:
nvav1enc.set_property("rc-mode", "cbr")
nvav1enc.set_property("gop-size", -1 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
nvav1enc.set_property("strict-gop", True)
nvav1enc.set_property("b-adapt", False)
nvav1enc.set_property("rc-lookahead", 0)
nvav1enc.set_property("vbv-buffer-size", int((self.fec_video_bitrate + self.framerate - 1) // self.framerate * self.vbv_multiplier_nv))
if Gst.version().major == 1 and 20 < Gst.version().minor <= 24:
nvav1enc.set_property("b-frames", 0)
nvav1enc.set_property("zero-reorder-delay", True)
else:
nvav1enc.set_property("bframes", 0)
nvav1enc.set_property("zerolatency", True)
if Gst.version().major == 1 and Gst.version().minor > 22:
nvav1enc.set_property("preset", "p4")
nvav1enc.set_property("tune", "ultra-low-latency")
nvav1enc.set_property("multi-pass", "two-pass-quarter")
else:
nvav1enc.set_property("preset", "low-latency-hq")
elif self.encoder in ["vah264enc"]:
# colorspace conversion
if self.gpu_id > 0:
vapostproc = Gst.ElementFactory.make("varenderD{}postproc".format(128 + self.gpu_id), "vapostproc")
else:
vapostproc = Gst.ElementFactory.make("vapostproc")
vapostproc.set_property("scale-method", "fast")
vapostproc.set_property("qos", True)
vapostproc_caps = Gst.caps_from_string("video/x-raw(memory:VAMemory)")
vapostproc_caps.set_value("format", "NV12")
vapostproc_capsfilter = Gst.ElementFactory.make("capsfilter")
vapostproc_capsfilter.set_property("caps", vapostproc_caps)
# encoder
if self.gpu_id > 0:
vah264enc = Gst.ElementFactory.make("varenderD{}h264enc".format(128 + self.gpu_id), "vaenc")
if vah264enc is None:
vah264enc = Gst.ElementFactory.make("varenderD{}h264lpenc".format(128 + self.gpu_id), "vaenc")
else:
vah264enc = Gst.ElementFactory.make("vah264enc", "vaenc")
if vah264enc is None:
vah264enc = Gst.ElementFactory.make("vah264lpenc", "vaenc")
vah264enc.set_property("aud", False)
vah264enc.set_property("b-frames", 0)
# Set VBV/HRD buffer size (kbits) to optimize for live streaming
vah264enc.set_property("cpb-size", int((self.fec_video_bitrate + self.framerate - 1) // self.framerate * self.vbv_multiplier_va))
vah264enc.set_property("dct8x8", False)
vah264enc.set_property("key-int-max", 1024 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
vah264enc.set_property("mbbrc", "disabled")
vah264enc.set_property("num-slices", 4)
vah264enc.set_property("ref-frames", 1)
vah264enc.set_property("rate-control", "cbr")
vah264enc.set_property("target-usage", 6)
vah264enc.set_property("bitrate", self.fec_video_bitrate)
elif self.encoder in ["vah265enc"]:
# colorspace conversion
if self.gpu_id > 0:
vapostproc = Gst.ElementFactory.make("varenderD{}postproc".format(128 + self.gpu_id), "vapostproc")
else:
vapostproc = Gst.ElementFactory.make("vapostproc")
vapostproc.set_property("scale-method", "fast")
vapostproc.set_property("qos", True)
vapostproc_caps = Gst.caps_from_string("video/x-raw(memory:VAMemory)")
vapostproc_caps.set_value("format", "NV12")
vapostproc_capsfilter = Gst.ElementFactory.make("capsfilter")
vapostproc_capsfilter.set_property("caps", vapostproc_caps)
# encoder
if self.gpu_id > 0:
vah265enc = Gst.ElementFactory.make("varenderD{}h265enc".format(128 + self.gpu_id), "vaenc")
if vah265enc is None:
vah265enc = Gst.ElementFactory.make("varenderD{}h265lpenc".format(128 + self.gpu_id), "vaenc")
else:
vah265enc = Gst.ElementFactory.make("vah265enc", "vaenc")
if vah265enc is None:
vah265enc = Gst.ElementFactory.make("vah265lpenc", "vaenc")
vah265enc.set_property("aud", False)
vah265enc.set_property("b-frames", 0)
# Set VBV/HRD buffer size (kbits) to optimize for live streaming
vah265enc.set_property("cpb-size", int((self.fec_video_bitrate + self.framerate - 1) // self.framerate * self.vbv_multiplier_va))
vah265enc.set_property("key-int-max", 1024 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
vah265enc.set_property("mbbrc", "disabled")
vah265enc.set_property("num-slices", 4)
vah265enc.set_property("ref-frames", 1)
vah265enc.set_property("rate-control", "cbr")
vah265enc.set_property("target-usage", 6)
vah265enc.set_property("bitrate", self.fec_video_bitrate)
elif self.encoder in ["vavp9enc"]:
# colorspace conversion
if self.gpu_id > 0:
vapostproc = Gst.ElementFactory.make("varenderD{}postproc".format(128 + self.gpu_id), "vapostproc")
else:
vapostproc = Gst.ElementFactory.make("vapostproc")
vapostproc.set_property("scale-method", "fast")
vapostproc.set_property("qos", True)
vapostproc_caps = Gst.caps_from_string("video/x-raw(memory:VAMemory)")
vapostproc_caps.set_value("format", "NV12")
vapostproc_capsfilter = Gst.ElementFactory.make("capsfilter")
vapostproc_capsfilter.set_property("caps", vapostproc_caps)
# encoder
if self.gpu_id > 0:
vavp9enc = Gst.ElementFactory.make("varenderD{}vp9enc".format(128 + self.gpu_id), "vaenc")
if vavp9enc is None:
vavp9enc = Gst.ElementFactory.make("varenderD{}vp9lpenc".format(128 + self.gpu_id), "vaenc")
else:
vavp9enc = Gst.ElementFactory.make("vavp9enc", "vaenc")
if vavp9enc is None:
vavp9enc = Gst.ElementFactory.make("vavp9lpenc", "vaenc")
# Set VBV/HRD buffer size (kbits) to optimize for live streaming
vavp9enc.set_property("cpb-size", int((self.fec_video_bitrate + self.framerate - 1) // self.framerate * self.vbv_multiplier_va))
vavp9enc.set_property("hierarchical-level", 1)
vavp9enc.set_property("key-int-max", 1024 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
vavp9enc.set_property("mbbrc", "disabled")
vavp9enc.set_property("ref-frames", 1)
vavp9enc.set_property("rate-control", "cbr")
vavp9enc.set_property("target-usage", 6)
vavp9enc.set_property("bitrate", self.fec_video_bitrate)
elif self.encoder in ["vaav1enc"]:
# colorspace conversion
if self.gpu_id > 0:
vapostproc = Gst.ElementFactory.make("varenderD{}postproc".format(128 + self.gpu_id), "vapostproc")
else:
vapostproc = Gst.ElementFactory.make("vapostproc")
vapostproc.set_property("scale-method", "fast")
vapostproc.set_property("qos", True)
vapostproc_caps = Gst.caps_from_string("video/x-raw(memory:VAMemory)")
vapostproc_caps.set_value("format", "NV12")
vapostproc_capsfilter = Gst.ElementFactory.make("capsfilter")
vapostproc_capsfilter.set_property("caps", vapostproc_caps)
# encoder
if self.gpu_id > 0:
vaav1enc = Gst.ElementFactory.make("varenderD{}av1enc".format(128 + self.gpu_id), "vaenc")
if vaav1enc is None:
vaav1enc = Gst.ElementFactory.make("varenderD{}av1lpenc".format(128 + self.gpu_id), "vaenc")
else:
vaav1enc = Gst.ElementFactory.make("vaav1enc", "vaenc")
if vaav1enc is None:
vaav1enc = Gst.ElementFactory.make("vaav1lpenc", "vaenc")
# Set VBV/HRD buffer size (kbits) to optimize for live streaming
vaav1enc.set_property("cpb-size", int((self.fec_video_bitrate + self.framerate - 1) // self.framerate * self.vbv_multiplier_va))
vaav1enc.set_property("hierarchical-level", 1)
vaav1enc.set_property("key-int-max", 1024 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
vaav1enc.set_property("mbbrc", "disabled")
vaav1enc.set_property("ref-frames", 1)
vaav1enc.set_property("tile-groups", 16)
vaav1enc.set_property("rate-control", "cbr")
vaav1enc.set_property("target-usage", 6)
vaav1enc.set_property("bitrate", self.fec_video_bitrate)
elif self.encoder in ["x264enc"]:
# Videoconvert for colorspace conversion
videoconvert = Gst.ElementFactory.make("videoconvert")
videoconvert.set_property("n-threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
videoconvert.set_property("qos", True)
videoconvert_caps = Gst.caps_from_string("video/x-raw")
videoconvert_caps.set_value("format", "NV12")
videoconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
videoconvert_capsfilter.set_property("caps", videoconvert_caps)
# encoder
x264enc = Gst.ElementFactory.make("x264enc", "x264enc")
# Chromium has issues with more than four encoding slices
x264enc.set_property("threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
x264enc.set_property("aud", False)
x264enc.set_property("b-adapt", False)
x264enc.set_property("bframes", 0)
x264enc.set_property("dct8x8", False)
x264enc.set_property("insert-vui", True)
x264enc.set_property("key-int-max", 2147483647 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
x264enc.set_property("mb-tree", False)
x264enc.set_property("rc-lookahead", 0)
x264enc.set_property("sync-lookahead", 0)
# Set VBV/HRD buffer size (milliseconds) to optimize for live streaming
x264enc.set_property("vbv-buf-capacity", int((1000 + self.framerate - 1) // self.framerate * self.vbv_multiplier_sw))
x264enc.set_property("sliced-threads", True)
x264enc.set_property("byte-stream", True)
x264enc.set_property("pass", "cbr")
x264enc.set_property("speed-preset", "ultrafast")
x264enc.set_property("tune", "zerolatency")
x264enc.set_property("bitrate", self.fec_video_bitrate)
elif self.encoder in ["openh264enc"]:
# Videoconvert for colorspace conversion
videoconvert = Gst.ElementFactory.make("videoconvert")
videoconvert.set_property("n-threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
videoconvert.set_property("qos", True)
videoconvert_caps = Gst.caps_from_string("video/x-raw")
videoconvert_caps.set_value("format", "I420")
videoconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
videoconvert_capsfilter.set_property("caps", videoconvert_caps)
# encoder
openh264enc = Gst.ElementFactory.make("openh264enc", "openh264enc")
openh264enc.set_property("adaptive-quantization", False)
openh264enc.set_property("background-detection", False)
openh264enc.set_property("enable-frame-skip", False)
openh264enc.set_property("scene-change-detection", False)
openh264enc.set_property("usage-type", "screen")
openh264enc.set_property("complexity", "low")
openh264enc.set_property("gop-size", 2147483647 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
openh264enc.set_property("multi-thread", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
openh264enc.set_property("slice-mode", "n-slices")
# Chromium has issues with more than four encoding slices
openh264enc.set_property("num-slices", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
openh264enc.set_property("rate-control", "bitrate")
openh264enc.set_property("bitrate", self.fec_video_bitrate * 1000)
elif self.encoder in ["x265enc"]:
# Videoconvert for colorspace conversion
videoconvert = Gst.ElementFactory.make("videoconvert")
videoconvert.set_property("n-threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
videoconvert.set_property("qos", True)
videoconvert_caps = Gst.caps_from_string("video/x-raw")
videoconvert_caps.set_value("format", "I420")
videoconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
videoconvert_capsfilter.set_property("caps", videoconvert_caps)
# encoder
x265enc = Gst.ElementFactory.make("x265enc", "x265enc")
x265enc.set_property("option-string", "b-adapt=0:bframes=0:rc-lookahead=0:repeat-headers:pmode:wpp")
x265enc.set_property("key-int-max", 2147483647 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
x265enc.set_property("speed-preset", "ultrafast")
x265enc.set_property("tune", "zerolatency")
x265enc.set_property("bitrate", self.fec_video_bitrate)
elif self.encoder in ["vp8enc", "vp9enc"]:
videoconvert = Gst.ElementFactory.make("videoconvert")
videoconvert.set_property("n-threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
videoconvert.set_property("qos", True)
videoconvert_caps = Gst.caps_from_string("video/x-raw")
videoconvert_caps.set_value("format", "I420")
videoconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
videoconvert_capsfilter.set_property("caps", videoconvert_caps)
if self.encoder == "vp8enc":
vpenc = Gst.ElementFactory.make("vp8enc", "vpenc")
elif self.encoder == "vp9enc":
vpenc = Gst.ElementFactory.make("vp9enc", "vpenc")
vpenc.set_property("frame-parallel-decoding", True)
vpenc.set_property("row-mt", True)
# VPX Parameters
vpenc.set_property("threads", min(16, max(1, len(os.sched_getaffinity(0)) - 1)))
# Set VBV/HRD buffer size (milliseconds) to optimize for live streaming
vbv_buffer_size = int((1000 + self.framerate - 1) // self.framerate * self.vbv_multiplier_vp)
vpenc.set_property("buffer-initial-size", vbv_buffer_size)
vpenc.set_property("buffer-optimal-size", vbv_buffer_size)
vpenc.set_property("buffer-size", vbv_buffer_size)
vpenc.set_property("cpu-used", -16)
vpenc.set_property("deadline", 1)
vpenc.set_property("end-usage", "cbr")
vpenc.set_property("error-resilient", "default")
vpenc.set_property("keyframe-mode", "disabled")
vpenc.set_property("keyframe-max-dist", 2147483647 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
vpenc.set_property("lag-in-frames", 0)
vpenc.set_property("max-intra-bitrate", 250)
vpenc.set_property("multipass-mode", "first-pass")
vpenc.set_property("overshoot", 10)
vpenc.set_property("undershoot", 25)
vpenc.set_property("static-threshold", 0)
vpenc.set_property("tuning", "psnr")
vpenc.set_property("target-bitrate", self.fec_video_bitrate * 1000)
elif self.encoder in ["svtav1enc"]:
videoconvert = Gst.ElementFactory.make("videoconvert")
videoconvert.set_property("n-threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
videoconvert.set_property("qos", True)
videoconvert_caps = Gst.caps_from_string("video/x-raw")
videoconvert_caps.set_value("format", "I420")
videoconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
videoconvert_capsfilter.set_property("caps", videoconvert_caps)
svtav1enc = Gst.ElementFactory.make("svtav1enc", "svtav1enc")
svtav1enc.set_property("intra-period-length", -1 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
# svtav1enc.set_property("maximum-buffer-size", 150)
svtav1enc.set_property("preset", 10)
svtav1enc.set_property("logical-processors", min(24, max(1, len(os.sched_getaffinity(0)) - 1)))
svtav1enc.set_property("parameters-string", "rc=2:fast-decode=1:buf-initial-sz=100:buf-optimal-sz=120:maxsection-pct=250:lookahead=0:pred-struct=1")
svtav1enc.set_property("target-bitrate", self.fec_video_bitrate)
elif self.encoder in ["av1enc"]:
videoconvert = Gst.ElementFactory.make("videoconvert")
videoconvert.set_property("n-threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
videoconvert.set_property("qos", True)
videoconvert_caps = Gst.caps_from_string("video/x-raw")
videoconvert_caps.set_value("format", "I420")
videoconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
videoconvert_capsfilter.set_property("caps", videoconvert_caps)
av1enc = Gst.ElementFactory.make("av1enc", "av1enc")
# av1enc.set_property("buf-initial-sz", 100)
# av1enc.set_property("buf-optimal-sz", 120)
# av1enc.set_property("buf-sz", 150)
av1enc.set_property("cpu-used", 10)
av1enc.set_property("end-usage", "cbr")
av1enc.set_property("keyframe-max-dist", 2147483647 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
av1enc.set_property("lag-in-frames", 0)
av1enc.set_property("overshoot-pct", 10)
av1enc.set_property("row-mt", True)
av1enc.set_property("usage-profile", "realtime")
av1enc.set_property("tile-columns", 2)
av1enc.set_property("tile-rows", 2)
av1enc.set_property("threads", min(24, max(1, len(os.sched_getaffinity(0)) - 1)))
av1enc.set_property("target-bitrate", self.fec_video_bitrate)
elif self.encoder in ["rav1enc"]:
videoconvert = Gst.ElementFactory.make("videoconvert")
videoconvert.set_property("n-threads", min(4, max(1, len(os.sched_getaffinity(0)) - 1)))
videoconvert.set_property("qos", True)
videoconvert_caps = Gst.caps_from_string("video/x-raw")
videoconvert_caps.set_value("format", "I420")
videoconvert_capsfilter = Gst.ElementFactory.make("capsfilter")
videoconvert_capsfilter.set_property("caps", videoconvert_caps)
rav1enc = Gst.ElementFactory.make("rav1enc", "rav1enc")
rav1enc.set_property("low-latency", True)
rav1enc.set_property("max-key-frame-interval", 715827882 if self.keyframe_distance == -1.0 else self.keyframe_frame_distance)
rav1enc.set_property("rdo-lookahead-frames", 0)
rav1enc.set_property("reservoir-frame-delay", 12)
rav1enc.set_property("speed-preset", 10)
rav1enc.set_property("tiles", 16)
rav1enc.set_property("threads", min(24, max(1, len(os.sched_getaffinity(0)) - 1)))
rav1enc.set_property("bitrate", self.fec_video_bitrate * 1000)
else:
raise GSTWebRTCAppError("Unsupported encoder for pipeline: %s" % self.encoder)
if "h264" in self.encoder or "x264" in self.encoder:
# Set the capabilities for the H.264 codec.
h264enc_caps = Gst.caps_from_string("video/x-h264")
# Sets the H.264 encoding profile to one compatible with WebRTC.
# Main profile includes CABAC and is compatible with Chrome.
# In low-latency encoding, High profile features are not utilized.
# Browsers only support specific H.264 profiles and they are
# coded in the RTP payload type set by the rtph264pay_caps below.
h264enc_caps.set_value("profile", "main")
# Stream-oriented H.264 codec
h264enc_caps.set_value("stream-format", "byte-stream")
# Create a capability filter for the h264enc_caps.
h264enc_capsfilter = Gst.ElementFactory.make("capsfilter")
h264enc_capsfilter.set_property("caps", h264enc_caps)
# Create the rtph264pay element to convert buffers into
# RTP packets that are sent over the connection transport.
rtph264pay = Gst.ElementFactory.make("rtph264pay")
rtph264pay.set_property("mtu", 1200)
# Default aggregate mode for WebRTC
rtph264pay.set_property("aggregate-mode", "zero-latency")
# Send SPS and PPS Insertion with every IDR frame
rtph264pay.set_property("config-interval", -1)
# Add WebRTC RTP extensions
extensions_return = self.rtp_add_extensions(rtph264pay)
if not extensions_return:
logger.warning("WebRTC RTP extension configuration failed with video, this may lead to suboptimal performance")
# Set the capabilities for the rtph264pay element.
rtph264pay_caps = Gst.caps_from_string("application/x-rtp")
# Set the payload type to video.
rtph264pay_caps.set_value("media", "video")
rtph264pay_caps.set_value("clock-rate", 90000)
# Set the video encoding name to match our encoded format.
rtph264pay_caps.set_value("encoding-name", "H264")
# Set the payload type that matches the encoding profile.
# Fake to the baseline profile in the SDP for Firefox
# Main or High profile can still be decoded
# Other payloads can be derived using WebRTC specification:
# https://tools.ietf.org/html/rfc6184#section-8.2.1
rtph264pay_caps.set_value("payload", 97)
# Set caps that help with frame retransmits that will avoid screen freezing on packet loss.
rtph264pay_caps.set_value("rtcp-fb-nack-pli", True)
rtph264pay_caps.set_value("rtcp-fb-ccm-fir", True)
rtph264pay_caps.set_value("rtcp-fb-x-gstreamer-fir-as-repair", True)
# Create a capability filter for the rtph264pay_caps.
rtph264pay_capsfilter = Gst.ElementFactory.make("capsfilter")
rtph264pay_capsfilter.set_property("caps", rtph264pay_caps)
elif "h265" in self.encoder or "x265" in self.encoder:
h265enc_caps = Gst.caps_from_string("video/x-h265")
h265enc_caps.set_value("profile", "main")
h265enc_caps.set_value("stream-format", "byte-stream")
h265enc_capsfilter = Gst.ElementFactory.make("capsfilter")
h265enc_capsfilter.set_property("caps", h265enc_caps)
rtph265pay = Gst.ElementFactory.make("rtph265pay")
rtph265pay.set_property("mtu", 1200)
rtph265pay.set_property("aggregate-mode", "zero-latency")
rtph265pay.set_property("config-interval", -1)
extensions_return = self.rtp_add_extensions(rtph265pay)
if not extensions_return:
logger.warning("WebRTC RTP extension configuration failed with video, this may lead to suboptimal performance")
rtph265pay_caps = Gst.caps_from_string("application/x-rtp")
rtph265pay_caps.set_value("media", "video")
rtph265pay_caps.set_value("clock-rate", 90000)
rtph265pay_caps.set_value("encoding-name", "H265")
rtph265pay_caps.set_value("payload", 100)
rtph265pay_caps.set_value("rtcp-fb-nack-pli", True)
rtph265pay_caps.set_value("rtcp-fb-ccm-fir", True)
rtph265pay_caps.set_value("rtcp-fb-x-gstreamer-fir-as-repair", True)
rtph265pay_capsfilter = Gst.ElementFactory.make("capsfilter")
rtph265pay_capsfilter.set_property("caps", rtph265pay_caps)
elif "vp8" in self.encoder:
vpenc_caps = Gst.caps_from_string("video/x-vp8")
vpenc_capsfilter = Gst.ElementFactory.make("capsfilter")
vpenc_capsfilter.set_property("caps", vpenc_caps)
rtpvppay = Gst.ElementFactory.make("rtpvp8pay", "rtpvppay")
rtpvppay.set_property("mtu", 1200)
rtpvppay.set_property("picture-id-mode", "15-bit")
extensions_return = self.rtp_add_extensions(rtpvppay)
if not extensions_return:
logger.warning("WebRTC RTP extension configuration failed with video, this may lead to suboptimal performance")
rtpvppay_caps = Gst.caps_from_string("application/x-rtp")
rtpvppay_caps.set_value("media", "video")
rtpvppay_caps.set_value("clock-rate", 90000)
rtpvppay_caps.set_value("encoding-name", "VP8")
rtpvppay_caps.set_value("payload", 96)
rtpvppay_caps.set_value("rtcp-fb-nack-pli", True)
rtpvppay_caps.set_value("rtcp-fb-ccm-fir", True)
rtpvppay_caps.set_value("rtcp-fb-x-gstreamer-fir-as-repair", True)
rtpvppay_capsfilter = Gst.ElementFactory.make("capsfilter")
rtpvppay_capsfilter.set_property("caps", rtpvppay_caps)
elif "vp9" in self.encoder:
vpenc_caps = Gst.caps_from_string("video/x-vp9")
vpenc_capsfilter = Gst.ElementFactory.make("capsfilter")
vpenc_capsfilter.set_property("caps", vpenc_caps)
rtpvppay = Gst.ElementFactory.make("rtpvp9pay", "rtpvppay")
rtpvppay.set_property("mtu", 1200)
rtpvppay.set_property("picture-id-mode", "15-bit")
extensions_return = self.rtp_add_extensions(rtpvppay)
if not extensions_return:
logger.warning("WebRTC RTP extension configuration failed with video, this may lead to suboptimal performance")
rtpvppay_caps = Gst.caps_from_string("application/x-rtp")
rtpvppay_caps.set_value("media", "video")
rtpvppay_caps.set_value("clock-rate", 90000)
rtpvppay_caps.set_value("encoding-name", "VP9")
rtpvppay_caps.set_value("payload", 98)
rtpvppay_caps.set_value("rtcp-fb-nack-pli", True)
rtpvppay_caps.set_value("rtcp-fb-ccm-fir", True)
rtpvppay_caps.set_value("rtcp-fb-x-gstreamer-fir-as-repair", True)
rtpvppay_capsfilter = Gst.ElementFactory.make("capsfilter")
rtpvppay_capsfilter.set_property("caps", rtpvppay_caps)
elif "av1" in self.encoder:
av1enc_caps = Gst.caps_from_string("video/x-av1")
av1enc_caps.set_value("parsed", True)
av1enc_caps.set_value("stream-format", "obu-stream")
av1enc_capsfilter = Gst.ElementFactory.make("capsfilter")
av1enc_capsfilter.set_property("caps", av1enc_caps)
rtpav1pay = Gst.ElementFactory.make("rtpav1pay")
rtpav1pay.set_property("mtu", 1200)
extensions_return = self.rtp_add_extensions(rtpav1pay)
if not extensions_return:
logger.warning("WebRTC RTP extension configuration failed with video, this may lead to suboptimal performance")
rtpav1pay_caps = Gst.caps_from_string("application/x-rtp")
rtpav1pay_caps.set_value("media", "video")
rtpav1pay_caps.set_value("clock-rate", 90000)
rtpav1pay_caps.set_value("encoding-name", "AV1")
rtpav1pay_caps.set_value("payload", 96)
rtpav1pay_caps.set_value("rtcp-fb-nack-pli", True)
rtpav1pay_caps.set_value("rtcp-fb-ccm-fir", True)
rtpav1pay_caps.set_value("rtcp-fb-x-gstreamer-fir-as-repair", True)
rtpav1pay_capsfilter = Gst.ElementFactory.make("capsfilter")
rtpav1pay_capsfilter.set_property("caps", rtpav1pay_caps)
# Add all elements to the pipeline.
pipeline_elements = [self.ximagesrc, self.ximagesrc_capsfilter]
# ADD_ENCODER: add new encoder elements to this list
if self.encoder in ["nvh264enc"]:
pipeline_elements += [cudaupload, cudaconvert, cudaconvert_capsfilter, nvh264enc, h264enc_capsfilter, rtph264pay, rtph264pay_capsfilter]
elif self.encoder in ["nvh265enc"]:
pipeline_elements += [cudaupload, cudaconvert, cudaconvert_capsfilter, nvh265enc, h265enc_capsfilter, rtph265pay, rtph265pay_capsfilter]
elif self.encoder in ["nvav1enc"]:
pipeline_elements += [cudaupload, cudaconvert, cudaconvert_capsfilter, nvav1enc, av1enc_capsfilter, rtpav1pay, rtpav1pay_capsfilter]
elif self.encoder in ["vah264enc"]:
pipeline_elements += [vapostproc, vapostproc_capsfilter, vah264enc, h264enc_capsfilter, rtph264pay, rtph264pay_capsfilter]
elif self.encoder in ["vah265enc"]:
pipeline_elements += [vapostproc, vapostproc_capsfilter, vah265enc, h265enc_capsfilter, rtph265pay, rtph265pay_capsfilter]
elif self.encoder in ["vavp9enc"]:
pipeline_elements += [vapostproc, vapostproc_capsfilter, vavp9enc, vpenc_capsfilter, rtpvppay, rtpvppay_capsfilter]
elif self.encoder in ["vaav1enc"]:
pipeline_elements += [vapostproc, vapostproc_capsfilter, vaav1enc, av1enc_capsfilter, rtpav1pay, rtpav1pay_capsfilter]
elif self.encoder in ["x264enc"]:
pipeline_elements += [videoconvert, videoconvert_capsfilter, x264enc, h264enc_capsfilter, rtph264pay, rtph264pay_capsfilter]
elif self.encoder in ["openh264enc"]:
pipeline_elements += [videoconvert, videoconvert_capsfilter, openh264enc, h264enc_capsfilter, rtph264pay, rtph264pay_capsfilter]
elif self.encoder in ["x265enc"]:
pipeline_elements += [videoconvert, videoconvert_capsfilter, x265enc, h265enc_capsfilter, rtph265pay, rtph265pay_capsfilter]
elif self.encoder in ["vp8enc", "vp9enc"]:
pipeline_elements += [videoconvert, videoconvert_capsfilter, vpenc, vpenc_capsfilter, rtpvppay, rtpvppay_capsfilter]
elif self.encoder in ["svtav1enc"]:
pipeline_elements += [videoconvert, videoconvert_capsfilter, svtav1enc, av1enc_capsfilter, rtpav1pay, rtpav1pay_capsfilter]
elif self.encoder in ["av1enc"]:
pipeline_elements += [videoconvert, videoconvert_capsfilter, av1enc, av1enc_capsfilter, rtpav1pay, rtpav1pay_capsfilter]
elif self.encoder in ["rav1enc"]:
pipeline_elements += [videoconvert, videoconvert_capsfilter, rav1enc, av1enc_capsfilter, rtpav1pay, rtpav1pay_capsfilter]
for pipeline_element in pipeline_elements:
self.pipeline.add(pipeline_element)
# Link the pipeline elements and raise exception of linking fails
# due to incompatible element pad capabilities.
pipeline_elements += [self.webrtcbin]
for i in range(len(pipeline_elements) - 1):
if not Gst.Element.link(pipeline_elements[i], pipeline_elements[i + 1]):
raise GSTWebRTCAppError("Failed to link {} -> {}".format(pipeline_elements[i].get_name(), pipeline_elements[i + 1].get_name()))
# Enable NACKs on the transceiver with video streams, helps with retransmissions and freezing when packets are dropped.
transceiver = self.webrtcbin.emit("get-transceiver", 0)
transceiver.set_property("do-nack", True)
transceiver.set_property("fec-type", GstWebRTC.WebRTCFECType.ULP_RED if self.video_packetloss_percent > 0 else GstWebRTC.WebRTCFECType.NONE)
transceiver.set_property("fec-percentage", self.video_packetloss_percent)
# [END build_video_pipeline]