forked from steveseguin/raspberry_ninja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
publish.py
2558 lines (2208 loc) · 121 KB
/
publish.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
import random
import ssl
import websockets
import asyncio
import os
import sys
import json
import argparse
import time
import gi
import threading
import socket
import re
import traceback
import subprocess
import struct
try:
import hashlib
from urllib.parse import urlparse
except Exception as e:
pass
try:
import numpy as np
import multiprocessing
from multiprocessing import shared_memory
except Exception as e:
pass
try:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes, padding
from cryptography.hazmat.backends import default_backend
except ImportError as e:
raise ImportError("Run `pip install cryptography` to install the dependencies needed for passwords") from e
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GObject
gi.require_version('GstWebRTC', '1.0')
from gi.repository import GstWebRTC
gi.require_version('GstSdp', '1.0')
from gi.repository import GstSdp
try:
from gi.repository import GLib
except:
pass
#os.environ['GST_DEBUG'] = '3,ndisink:7,videorate:5,videoscale:5,videoconvert:5'
def generate_unique_ndi_name(base_name):
return f"{base_name}_{int(time.time())}"
def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
print("!!! Unhandled exception !!!")
print("Type:", exc_type)
print("Value:", exc_value)
print("Traceback:", ''.join(traceback.format_tb(exc_traceback)))
tb = traceback.extract_tb(exc_traceback)
for frame in tb:
print(f"File \"{frame.filename}\", line {frame.lineno}, in {frame.name}")
sys.excepthook = handle_unhandled_exception
def get_exception_info(E):
tb = traceback.extract_tb(E.__traceback__)
error_line = tb[-1].lineno
error_file = tb[-1].filename
if len(tb) >= 2:
caller = tb[-2]
caller_line = caller.lineno
caller_file = caller.filename
else:
caller_line = "unknown"
caller_file = "unknown"
return (
f"{type(E).__name__} at line {error_line} in {error_file}: {E}\n"
f"Called from line {caller_line} in {caller_file}"
)
def enableLEDs(level=False):
try:
GPIO
except Exception as e:
return
global LED_Level, P_R
if level!=False:
LED_Level = level
p_R.start(0) # Initial duty Cycle = 0(leds off)
p_R.ChangeDutyCycle(LED_Level) # Change duty cycle
def disableLEDs():
try:
GPIO
except Exception as e:
return
global pin, P_R
p_R.stop()
GPIO.output(pin, GPIO.HIGH) # Turn off all leds
GPIO.cleanup()
def hex_to_ansi(hex_color):
hex_color = hex_color.lstrip('#')
if len(hex_color)==6:
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
elif len(hex_color)==3:
r = int(hex_color[0:1]+hex_color[0:1], 16)
g = int(hex_color[1:2]+hex_color[1:2], 16)
b = int(hex_color[2:3]+hex_color[2:3], 16)
else:
return hex_color
ansi_color = 16 + (36 * int(r / 255 * 5)) + (6 * int(g / 255 * 5)) + int(b / 255 * 5)
return f"\033[38;5;{ansi_color}m"
def printc(message, color_code=None):
reset_color = "\033[0m"
if color_code is not None:
color_code = hex_to_ansi(color_code)
colored_message = f"{color_code}{message}{reset_color}"
print(colored_message)
else:
print(message)
def printwin(message):
printc("<= "+message,"93F")
def printwout(message):
printc("=> "+message,"9F3")
def printin(message):
printc("<= "+message,"F6A")
def printout(message):
printc("=> "+message,"6F6")
def printwarn(message):
printc(message,"FF0")
def check_drm_displays():
try:
result = subprocess.run(['drm_info'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
output = result.stdout.strip()
drm_info = json.loads(output)
connected_displays = [connector for connector in drm_info['connectors'] if connector['status'] == 'connected']
if connected_displays:
print("Display(s) connected:")
for display in connected_displays:
print(display)
return True
else:
print("No display connected.")
return False
else:
print(f"Error running drm_info: {result.stderr}")
return False
except Exception as e:
print(f"Exception occurred: {e}")
return False
def replace_ssrc_and_cleanup_sdp(sdp): ## fix for audio-only gstreamer -> chrome
def generate_ssrc():
return str(random.randint(0, 0xFFFFFFFF))
lines = sdp.split('\r\n')
in_audio_section = False
new_ssrc = generate_ssrc()
for i in range(len(lines)):
if lines[i].startswith('m=audio '):
in_audio_section = True
elif lines[i].startswith('m=') and not lines[i].startswith('m=audio '):
in_audio_section = False
if in_audio_section and lines[i].startswith('a=ssrc:'):
lines[i] = re.sub(r'a=ssrc:\d+', f'a=ssrc:{new_ssrc}', lines[i])
return '\r\n'.join(lines)
def generateHash(input_str, length=None):
input_bytes = input_str.encode('utf-8')
sha256_hash = hashlib.sha256(input_bytes).digest()
if length:
hash_hex = sha256_hash[:int(length // 2)].hex()
else:
hash_hex = sha256_hash.hex()
return hash_hex
def convert_string_to_bytes(input_str):
return input_str.encode('utf-8')
def to_hex_string(byte_data):
return ''.join(f'{b:02x}' for b in byte_data)
def to_byte_array(hex_str):
return bytes.fromhex(hex_str)
def generate_key(phrase):
return hashlib.sha256(phrase.encode()).digest()
def pad_message(message):
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(message.encode('utf-8')) + padder.finalize()
return padded_data
def unpad_message(padded_message):
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
try:
data = unpadder.update(padded_message) + unpadder.finalize()
return data
except ValueError as e:
print(f"Padding error: {e}")
return None
def encrypt_message(message, phrase):
try:
message = json.dumps(message)
except Exception as E:
printwarn(get_exception_info(E))
key = generate_key(phrase)
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
padded_message = pad_message(message)
encrypted_message = encryptor.update(padded_message) + encryptor.finalize()
return to_hex_string(encrypted_message), to_hex_string(iv)
def decrypt_message(encrypted_data, iv, phrase):
key = generate_key(phrase)
encrypted_data_bytes = to_byte_array(encrypted_data)
iv_bytes = to_byte_array(iv)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv_bytes), backend=default_backend())
decryptor = cipher.decryptor()
try:
decrypted_padded_message = decryptor.update(encrypted_data_bytes) + decryptor.finalize()
unpadded_message = unpad_message(decrypted_padded_message)
if unpadded_message is not None:
return unpadded_message.decode('utf-8')
else:
return None
except (UnicodeDecodeError, ValueError) as e:
print(f"Error decoding message: {e}")
return None
def setup_ice_servers(webrtc):
try:
# STUN servers
webrtc.set_property('stun-server', "stun://stun.cloudflare.com:3478")
webrtc.set_property('stun-server', "stun://stun.l.google.com:19302")
# TURN server
turn_server = "turn://vdoninja:[email protected]:3478"
webrtc.emit('add-turn-server', turn_server)
except Exception as E:
printwarn(get_exception_info(E))
class WebRTCClient:
def __init__(self, params):
self.pipeline = params.pipeline
self.conn = None
self.pipe = None
self.h264 = params.h264
self.vp8 = params.vp8
self.pipein = params.pipein
self.bitrate = params.bitrate
self.max_bitrate = params.bitrate
self.server = params.server
self.stream_id = params.streamid
self.view = params.view
self.room_name = params.room
self.room_hashcode = None
self.multiviewer = params.multiviewer
self.record = params.record
self.streamin = params.streamin
self.ndiout = params.ndiout
self.fdsink = params.fdsink
self.filesink = None
self.framebuffer = params.framebuffer
self.midi = params.midi
self.nored = params.nored
self.noqos = params.noqos
self.midi_thread = None
self.midiout = None
self.midiout_ports = None
self.puuid = params.puuid
self.clients = {}
self.rotate = int(params.rotate)
self.save_file = params.save
self.noaudio = params.noaudio
self.novideo = params.novideo
self.counter = 0
self.shared_memory = False
self.trigger_socket = False
self.processing = False
self.buffer = params.buffer
self.password = params.password
self.hostname = params.hostname
self.hashcode = ""
self.salt = ""
self.aom = params.aom
self.av1 = params.av1
self.socketout = params.socketout
self.socketport = params.socketport
self.socket = None
try:
if self.password:
parsed_url = urlparse(self.hostname)
hostname_parts = parsed_url.hostname.split(".")
self.salt = ".".join(hostname_parts[-2:])
self.hashcode = generateHash(self.password+self.salt, 6)
if self.room_name:
self.room_hashcode = generateHash(self.room_name+self.password+self.salt, 16)
except Exception as E:
printwarn(get_exception_info(E))
if self.save_file:
self.pipe = Gst.parse_launch(self.pipeline)
setup_ice_servers(self.pipe.get_by_name('sendrecv'))
self.pipe.set_state(Gst.State.PLAYING)
print("RECORDING TO DISK STARTED")
async def connect(self):
print("Connecting to handshake server")
sslctx = ssl.create_default_context()
self.conn = await websockets.connect(self.server, ssl=sslctx)
if self.room_hashcode:
if self.streamin:
await self.sendMessageAsync({"request":"joinroom","roomid":self.room_hashcode})
else:
await self.sendMessageAsync({"request":"joinroom","roomid":self.room_hashcode,"streamID":self.stream_id+self.hashcode})
printwout("joining room (hashed)")
elif self.room_name:
if self.streamin:
await self.sendMessageAsync({"request":"joinroom","roomid":self.room_name})
else:
await self.sendMessageAsync({"request":"joinroom","roomid":self.room_name,"streamID":self.stream_id+self.hashcode})
printwout("joining room")
elif self.streamin:
await self.sendMessageAsync({"request":"play","streamID":self.streamin+self.hashcode})
printwout("requesting stream")
else:
await self.sendMessageAsync({"request":"seed","streamID":self.stream_id+self.hashcode})
printwout("seed start")
def sendMessage(self, msg): # send message to wss
if self.puuid:
msg['from'] = self.puuid
client = None
if "UUID" in msg and msg['UUID'] in self.clients:
client = self.clients[msg['UUID']]
if client and client['send_channel']:
try:
msgJSON = json.dumps(msg)
client['send_channel'].emit('send-string', msgJSON)
printout("a message was sent via datachannels: "+msgJSON[:60])
except Exception as e:
try:
if self.password:
#printc("Password","0F3")
if "candidate" in msg:
msg['candidate'], msg['vector'] = encrypt_message(msg['candidate'], self.password+self.salt)
if "candidates" in msg:
msg['candidates'], msg['vector'] = encrypt_message(msg['candidates'], self.password+self.salt)
if "description" in msg:
msg['description'], msg['vector'] = encrypt_message(msg['description'], self.password+self.salt)
msgJSON = json.dumps(msg)
loop = asyncio.new_event_loop()
loop.run_until_complete(self.conn.send(msgJSON))
printwout("a message was sent via websockets 2: "+msgJSON[:60])
except Exception as e:
printc(e,"F00")
else:
try:
if self.password:
# printc("Password","0F3")
if "candidate" in msg:
msg['candidate'], msg['vector'] = encrypt_message(msg['candidate'], self.password+self.salt)
if "candidates" in msg:
msg['candidates'], msg['vector'] = encrypt_message(msg['candidates'], self.password+self.salt)
if "description" in msg:
msg['description'], msg['vector'] = encrypt_message(msg['description'], self.password+self.salt)
msgJSON = json.dumps(msg)
loop = asyncio.new_event_loop()
loop.run_until_complete(self.conn.send(msgJSON))
printwout("a message was sent via websockets 1: "+msgJSON[:60])
except Exception as e:
printc(e,"F01")
async def sendMessageAsync(self, msg): # send message to wss
if self.puuid:
msg['from'] = self.puuid
client = None
if "UUID" in msg and msg['UUID'] in self.clients:
client = self.clients[msg['UUID']]
if client and client['send_channel']:
try:
msgJSON = json.dumps(msg)
client['send_channel'].emit('send-string', msgJSON)
printout("a message was sent via datachannels: "+msgJSON[:60])
except Exception as e:
try:
if self.password:
if "candidate" in msg:
msg['candidate'], msg['vector'] = encrypt_message(msg['candidate'], self.password+self.salt)
if "candidates" in msg:
msg['candidates'], msg['vector'] = encrypt_message(msg['candidates'], self.password+self.salt)
if "description" in msg:
msg['description'], msg['vector'] = encrypt_message(msg['description'], self.password+self.salt)
msgJSON = json.dumps(msg)
await self.conn.send(msgJSON)
printwout("a message was sent via websockets 2: "+msgJSON[:60])
except Exception as E:
printwarn(get_exception_info(E))
else:
try:
if self.password:
if "candidate" in msg:
msg['candidate'], msg['vector'] = encrypt_message(msg['candidate'], self.password+self.salt)
if "candidates" in msg:
msg['candidates'], msg['vector'] = encrypt_message(msg['candidates'], self.password+self.salt)
if "description" in msg:
msg['description'], msg['vector'] = encrypt_message(msg['description'], self.password+self.salt)
msgJSON = json.dumps(msg)
await self.conn.send(msgJSON)
printwout("a message was sent via websockets 1: "+msgJSON[:60])
except Exception as e:
printwarn(get_exception_info(E))
def setup_socket(self):
import socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.bind(('0.0.0.0', int(self.socketport)))
def on_new_socket_sample(self, sink):
sample = sink.emit("pull-sample")
if sample:
buffer = sample.get_buffer()
caps = sample.get_caps()
height = caps.get_structure(0).get_value("height")
width = caps.get_structure(0).get_value("width")
_, map_info = buffer.map(Gst.MapFlags.READ)
frame_data = map_info.data
# Send frame size
self.socket.sendto(struct.pack('!III', width, height, len(frame_data)), ('127.0.0.1', int(self.socketport)))
print("Sending")
# Send frame data in chunks
chunk_size = 65507 # Maximum safe UDP packet size
for i in range(0, len(frame_data), chunk_size):
chunk = frame_data[i:i+chunk_size]
self.socket.sendto(chunk, ('127.0.0.1', int(self.socketport)))
buffer.unmap(map_info)
return Gst.FlowReturn.OK
def new_sample(self, sink):
if self.processing:
return False
self.processing = True
try :
sample = sink.emit("pull-sample")
if sample:
buffer = sample.get_buffer()
caps = sample.get_caps()
height = int(caps.get_structure(0).get_int("height").value)
width = int(caps.get_structure(0).get_int("width").value)
frame_data = buffer.extract_dup(0, buffer.get_size())
np_frame_data = np.frombuffer(frame_data, dtype=np.uint8).reshape(height, width, 3)
print(np.shape(np_frame_data), np_frame_data[0,0,:])
frame_shape = (720 * 1280 * 3)
frame_buffer = np.ndarray(frame_shape+5, dtype=np.uint8, buffer=self.shared_memory.buf)
frame_buffer[5:5+width*height*3] = np_frame_data.flatten(order='K') # K means order as how ordered in memory
frame_buffer[0] = width/255
frame_buffer[1] = width%255
frame_buffer[2] = height/255
frame_buffer[3] = height%255
frame_buffer[4] = self.counter%255
self.counter+=1
self.trigger_socket.sendto(b"update", ("127.0.0.1", 12345))
except Exception as E:
printwarn(get_exception_info(E))
self.processing = False
return False
def on_incoming_stream(self, _, pad):
try:
if Gst.PadDirection.SRC != pad.direction:
print("pad direction wrong?")
return
caps = pad.get_current_caps()
name = caps.to_string()
print(f"Incoming stream caps: {name}")
if self.ndiout:
print("NDI OUT")
ndi_combiner = self.pipe.get_by_name("ndi_combiner")
ndi_sink = self.pipe.get_by_name("ndi_sink")
if not ndi_combiner:
print("Creating new NDI sink combiner")
ndi_combiner = Gst.ElementFactory.make("ndisinkcombiner", "ndi_combiner")
if not ndi_combiner:
print("Failed to create ndisinkcombiner element")
return
# Set properties
ndi_combiner.set_property("latency", 800_000_000) # 800ms
ndi_combiner.set_property("min-upstream-latency", 1_000_000_000) # 1000ms
ndi_combiner.set_property("start-time-selection", 1) # 1 corresponds to "first"
self.pipe.add(ndi_combiner)
ndi_combiner.sync_state_with_parent()
ret = ndi_combiner.set_state(Gst.State.PLAYING)
if ret == Gst.StateChangeReturn.FAILURE:
print("Failed to set ndi_combiner to PLAYING state")
return
if not ndi_sink:
print("Creating new NDI sink")
ndi_sink = Gst.ElementFactory.make("ndisink", "ndi_sink")
if not ndi_sink:
print("Failed to create ndisink element")
return
unique_ndi_name = generate_unique_ndi_name(self.ndiout)
ndi_sink.set_property("ndi-name", unique_ndi_name)
self.pipe.add(ndi_sink)
ndi_sink.sync_state_with_parent()
print(f"NDI sink name: {ndi_sink.get_property('ndi-name')}")
# Link ndi_combiner to ndi_sink
if not ndi_combiner.link(ndi_sink):
print("Failed to link ndi_combiner to ndi_sink")
return
if "video" in name:
print("NDI VIDEO OUT")
pad_name = "video"
rtp_caps_string = "application/x-rtp,media=(string)video,clock-rate=(int)90000,encoding-name=(string)H264"
elif "audio" in name:
print("NDI AUDIO OUT")
pad_name = "audio"
rtp_caps_string = "application/x-rtp,media=(string)audio,clock-rate=(int)48000,encoding-name=(string)OPUS"
else:
print("Unsupported media type:", name)
return
# Check if the pad already exists
target_pad = ndi_combiner.get_static_pad(pad_name)
if target_pad:
print(f"{pad_name.capitalize()} pad already exists, using existing pad")
else:
target_pad = ndi_combiner.request_pad(ndi_combiner.get_pad_template(pad_name), None, None)
if target_pad is None:
print(f"Failed to get {pad_name} pad from ndi_combiner")
print("Available pad templates:")
for template in ndi_combiner.get_pad_template_list():
print(f" {template.name_template}: {template.direction.value_name}")
print("Current pads:")
for pad in ndi_combiner.pads:
print(f" {pad.get_name()}: {pad.get_direction().value_name}")
return
print(f"Got {pad_name} pad: {target_pad.get_name()}")
# Create elements based on media type
if pad_name == "video":
elements = [
Gst.ElementFactory.make("capsfilter", f"{pad_name}_rtp_caps"),
Gst.ElementFactory.make("queue", f"{pad_name}_queue"),
Gst.ElementFactory.make("rtph264depay", "h264_depay"),
Gst.ElementFactory.make("h264parse", "h264_parse"),
Gst.ElementFactory.make("avdec_h264", "h264_decode"),
Gst.ElementFactory.make("videoconvert", "video_convert"),
Gst.ElementFactory.make("videoscale", "video_scale"),
Gst.ElementFactory.make("videorate", "video_rate"),
Gst.ElementFactory.make("capsfilter", "video_caps"),
]
elements[0].set_property("caps", Gst.Caps.from_string(rtp_caps_string))
elements[-1].set_property("caps", Gst.Caps.from_string("video/x-raw,format=UYVY,width=1280,height=720,framerate=30/1"))
else: # audio
elements = [
Gst.ElementFactory.make("capsfilter", f"{pad_name}_rtp_caps"),
Gst.ElementFactory.make("queue", f"{pad_name}_queue"),
Gst.ElementFactory.make("rtpopusdepay", "opus_depay"),
Gst.ElementFactory.make("opusdec", "opus_decode"),
Gst.ElementFactory.make("audioconvert", "audio_convert"),
Gst.ElementFactory.make("audioresample", "audio_resample"),
Gst.ElementFactory.make("capsfilter", "audio_caps"),
]
elements[0].set_property("caps", Gst.Caps.from_string(rtp_caps_string))
elements[-1].set_property("caps", Gst.Caps.from_string("audio/x-raw,format=F32LE,channels=2,rate=48000,layout=interleaved"))
if not all(elements):
print("Couldn't create all elements")
return
# Create a bin for the elements
bin_name = f"{pad_name}_bin"
element_bin = Gst.Bin.new(bin_name)
for element in elements:
element_bin.add(element)
# Link elements within the bin
for i in range(len(elements) - 1):
if not elements[i].link(elements[i+1]):
print(f"Failed to link {elements[i].get_name()} to {elements[i+1].get_name()}")
return
# Add ghost pads to the bin
sink_pad = elements[0].get_static_pad("sink")
ghost_sink = Gst.GhostPad.new("sink", sink_pad)
element_bin.add_pad(ghost_sink)
src_pad = elements[-1].get_static_pad("src")
ghost_src = Gst.GhostPad.new("src", src_pad)
element_bin.add_pad(ghost_src)
# Add the bin to the pipeline
self.pipe.add(element_bin)
element_bin.sync_state_with_parent()
# Link the bin to the ndi_combiner
if not element_bin.link_pads("src", ndi_combiner, target_pad.get_name()):
print(f"Failed to link {bin_name} to ndi_combiner:{target_pad.get_name()}")
print(f"Bin src caps: {ghost_src.query_caps().to_string()}")
print(f"Target pad caps: {target_pad.query_caps().to_string()}")
return
# Link the incoming pad to the bin
if not pad.link(ghost_sink):
print(f"Failed to link incoming pad to {bin_name}")
print(f"Incoming pad caps: {pad.query_caps().to_string()}")
print(f"Ghost sink pad caps: {ghost_sink.query_caps().to_string()}")
return
print(f"NDI {pad_name} pipeline set up successfully")
# Set the bin to PLAYING state
ret = element_bin.set_state(Gst.State.PLAYING)
if ret == Gst.StateChangeReturn.FAILURE:
print(f"Failed to set {bin_name} to PLAYING state")
return
print(f"All elements in {bin_name} set to PLAYING state")
elif "video" in name:
if self.novideo:
printc('Ignoring incoming video track', "F88")
out = Gst.parse_bin_from_description("queue ! fakesink", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
return
if self.ndiout:
# I'm handling this on elsewhere now
pass
elif self.socketout:
print("SOCKET VIDEO OUT")
out = Gst.parse_bin_from_description(
"queue ! rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! video/x-raw,format=BGR ! appsink name=appsink emit-signals=true", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
appsink = self.pipe.get_by_name('appsink')
appsink.connect("new-sample", self.on_new_socket_sample)
elif self.view:
print("DISPLAY OUTPUT MODE BEING SETUP")
outsink = "autovideosink"
if check_drm_displays():
printc('\nThere is at least one connected display.',"00F")
else:
printc('\n ! No connected displays found. Will try to use glimagesink instead of autovideosink',"F60")
outsink = "glimagesink sync=true"
if "VP8" in name:
out = Gst.parse_bin_from_description(
"queue ! rtpvp8depay ! decodebin ! queue max-size-buffers=0 max-size-time=0 ! videoconvert ! video/x-raw,format=RGB ! queue max-size-buffers=0 max-size-time=0 ! "+outsink, True)
elif "H264" in name:
out = Gst.parse_bin_from_description(
"queue ! rtph264depay ! h264parse ! openh264dec ! queue max-size-buffers=0 max-size-time=0 ! videoconvert ! video/x-raw,format=RGB ! queue max-size-buffers=0 max-size-time=0 ! "+outsink, True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
elif self.fdsink:
print("FD SINK OUT")
queue = Gst.ElementFactory.make("queue", "fd_queue")
depay = None
parse = None
decode = None
convert = Gst.ElementFactory.make("videoconvert", "fd_convert")
scale = Gst.ElementFactory.make("videoscale", "fd_scale")
caps_filter = Gst.ElementFactory.make("capsfilter", "fd_caps")
sink = Gst.ElementFactory.make("fdsink", "fd_sink")
if "VP8" in name:
depay = Gst.ElementFactory.make("rtpvp8depay", "vp8_depay")
decode = Gst.ElementFactory.make("vp8dec", "vp8_decode")
elif "H264" in name:
depay = Gst.ElementFactory.make("rtph264depay", "h264_depay")
parse = Gst.ElementFactory.make("h264parse", "h264_parse")
decode = Gst.ElementFactory.make("avdec_h264", "h264_decode")
else:
print("Unsupported video codec:", name)
return
if not all([queue, depay, decode, convert, scale, caps_filter, sink]):
print("Failed to create all elements")
return
# Set to raw video format, you can adjust based on your needs
caps_filter.set_property("caps", Gst.Caps.from_string("video/x-raw,format=RGB"))
self.pipe.add(queue)
self.pipe.add(depay)
if parse:
self.pipe.add(parse)
self.pipe.add(decode)
self.pipe.add(convert)
self.pipe.add(scale)
self.pipe.add(caps_filter)
self.pipe.add(sink)
# Link elements
if not queue.link(depay):
print("Failed to link queue and depay")
return
if parse:
if not depay.link(parse) or not parse.link(decode):
print("Failed to link depay, parse, and decode")
return
else:
if not depay.link(decode):
print("Failed to link depay and decode")
return
if not decode.link(convert):
print("Failed to link decode and convert")
return
if not convert.link(scale):
print("Failed to link convert and scale")
return
if not scale.link(caps_filter):
print("Failed to link scale and caps_filter")
return
if not caps_filter.link(sink):
print("Failed to link caps_filter and sink")
return
# Link the incoming pad to our queue
pad.link(queue.get_static_pad("sink"))
# Sync states
queue.sync_state_with_parent()
depay.sync_state_with_parent()
if parse:
parse.sync_state_with_parent()
decode.sync_state_with_parent()
convert.sync_state_with_parent()
scale.sync_state_with_parent()
caps_filter.sync_state_with_parent()
sink.sync_state_with_parent()
print("FD sink video pipeline set up successfully")
elif self.framebuffer: ## send raw data to ffmpeg or something I guess, using the stdout?
print("APP SINK OUT")
if "VP8" in name:
out = Gst.parse_bin_from_description("queue ! rtpvp8depay ! queue max-size-buffers=0 max-size-time=0 ! decodebin ! videoconvert ! video/x-raw,format=BGR ! queue max-size-buffers=2 leaky=downstream ! appsink name=appsink", True)
elif "H264" in name:
out = Gst.parse_bin_from_description("queue ! rtph264depay ! h264parse ! queue max-size-buffers=0 max-size-time=0 ! openh264dec ! videoconvert ! video/x-raw,format=BGR ! queue max-size-buffers=2 leaky=downstream ! appsink name=appsink", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
else:
printc('VIDEO record setup', "88F")
if self.pipe.get_by_name('filesink'):
print("VIDEO setup")
if "VP8" in name:
out = Gst.parse_bin_from_description("queue ! rtpvp8depay", True)
elif "H264" in name:
out = Gst.parse_bin_from_description("queue ! rtph264depay ! h264parse", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
out.link(self.pipe.get_by_name('filesink'))
pad.link(sink)
else:
if "VP8" in name:
out = Gst.parse_bin_from_description("queue ! rtpvp8depay ! mpegtsmux name=mux1 ! queue !"
+ "hlssink name=hlssink max-files=0 "
+ "target-duration=10 playlist-length=0 "
+ "location=" + "./" + self.streamin + "_"+str(int(time.time()))+"_segment_%05d.ts "
+ "playlist-location=" + "./" + self.streamin + "_"+str(int(time.time()))+".video.m3u8 " , True)
elif "H264" in name:
out = Gst.parse_bin_from_description("queue ! rtph264depay ! h264parse ! mpegtsmux name=mux1 ! queue ! "
+ "hlssink name=hlssink max-files=0 "
+ "target-duration=10 playlist-length=0 "
+ "location=" + "./" + self.streamin + "_"+str(int(time.time()))+"_segment_%05d.ts "
+ "playlist-location=" + "./" + self.streamin + "_"+str(int(time.time()))+".video.m3u8 " , True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
print("success video?")
if self.framebuffer:
frame_shape = (720, 1280, 3)
size = np.prod(frame_shape) * 3 # Total size in bytes
self.shared_memory = shared_memory.SharedMemory(create=True, size=size, name='psm_raspininja_streamid')
self.trigger_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # we don't bind, as the reader will be binding
print("*************")
print(self.shared_memory)
appsink = self.pipe.get_by_name('appsink')
appsink.set_property("emit-signals", True)
appsink.connect("new-sample", self.new_sample)
elif "audio" in name:
if self.noaudio:
printc('Ignoring incoming audio track', "F88")
out = Gst.parse_bin_from_description("queue ! fakesink", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
return
if self.ndiout:
# I'm handling this on elsewhere now
pass
elif self.view:
# if "OPUS" in name:
print("decode and play out the incoming audio")
out = Gst.parse_bin_from_description("queue ! rtpopusdepay ! opusparse ! opusdec ! audioconvert ! audioresample ! audio/x-raw,format=S16LE,rate=48000 ! autoaudiosink", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
elif self.fdsink:
#if "OPUS" in name:
out = Gst.parse_bin_from_description("queue ! rtpopusdepay ! opusparse ! opusdec ! audioconvert ! audioresample ! audio/x-raw,format=S16LE,rate=48000 ! fdsink", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
elif self.framebuffer:
out = Gst.parse_bin_from_description("queue ! fakesink", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
else:
if self.pipe.get_by_name('filesink'):
print("Audio being added after video")
if "OPUS" in name:
out = Gst.parse_bin_from_description("queue rtpopusdepay ! opusparse ! audio/x-opus,channel-mapping-family=0,channels=2,rate=48000", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
out.link(self.pipe.get_by_name('filesink'))
pad.link(sink)
else:
print("audio being saved...")
if "OPUS" in name:
out = Gst.parse_bin_from_description("queue ! rtpopusdepay ! opusparse ! audio/x-opus,channel-mapping-family=0,rate=48000 ! mpegtsmux name=mux2 ! queue ! multifilesink name=filesinkaudio sync=true location="+self.streamin+"_"+str(int(time.time()))+"_audio.%02d.ts next-file=5 max-file-duration="+str(10*Gst.SECOND), True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
print("success audio?")
except Exception as E:
print("============= ERROR =========")
printwarn(get_exception_info(E))
traceback.print_exc()
# Add this debugging information at the end of the function
print("Pipeline state after setup:")
print(self.pipe.get_state(0))
async def createPeer(self, UUID):
if UUID in self.clients:
client = self.clients[UUID]
else:
print("peer not yet created; error")
return
def on_offer_created(promise, _, __):
print("ON OFFER CREATED")
promise.wait()
reply = promise.get_reply()
offer = reply.get_value('offer')
promise = Gst.Promise.new()
client['webrtc'].emit('set-local-description', offer, promise)
promise.interrupt()
print("SEND SDP OFFER")
text = offer.sdp.as_text()
if ("96 96 96 96 96" in text):
printc("Patching SDP due to Gstreamer webRTC bug - none-unique line values","A6F")
text = text.replace(" 96 96 96 96 96", " 96 96 97 98 96")
text = text.replace("a=rtpmap:96 red/90000\r\n","a=rtpmap:97 red/90000\r\n")
text = text.replace("a=rtpmap:96 ulpfec/90000\r\n","a=rtpmap:98 ulpfec/90000\r\n")
text = text.replace("a=rtpmap:96 rtx/90000\r\na=fmtp:96 apt=96\r\n","")
elif self.nored and (" 96 96" in text): ## fix for older gstreamer is using --nored
printc("Patching SDP due to Gstreamer webRTC bug - issue with nored","A6F")
text = text.replace(" 96 96", " 96 97")
text = text.replace("a=rtpmap:96 ulpfec/90000\r\n","a=rtpmap:97 ulpfec/90000\r\n")
text = text.replace("a=rtpmap:96 rtx/90000\r\na=fmtp:96 apt=96\r\n","")
if self.novideo and not self.noaudio: # impacts audio and video as well, but chrome / firefox seems to handle it
printc("Patching SDP due to Gstreamer webRTC bug - audio-only issue", "A6F") # just chrome doesn't handle this
text = replace_ssrc_and_cleanup_sdp(text)
msg = {'description': {'type': 'offer', 'sdp': text}, 'UUID': client['UUID'], 'session': client['session'], 'streamID':self.stream_id+self.hashcode}
self.sendMessage(msg)
def on_new_tranceiver(element, trans):
print("ON NEW TRANS")
def on_negotiation_needed(element):
print("ON NEGO NEEDED")
promise = Gst.Promise.new_with_change_func(on_offer_created, element, None)
element.emit('create-offer', None, promise)
def send_ice_local_candidate_message(_, mlineindex, candidate):
if " TCP " in candidate: ## I Can revisit another time, but for now, this isn't needed: TODO: optimize
return
icemsg = {'candidates': [{'candidate': candidate, 'sdpMLineIndex': mlineindex}], 'session':client['session'], 'type':'local', 'UUID':client['UUID']}
self.sendMessage(icemsg)
def send_ice_remote_candidate_message(_, mlineindex, candidate):
icemsg = {'candidates': [{'candidate': candidate, 'sdpMLineIndex': mlineindex}], 'session':client['session'], 'type':'remote', 'UUID':client['UUID']}
self.sendMessage(icemsg)
def on_signaling_state(p1, p2):
print("ON SIGNALING STATE CHANGE: {}".format(client['webrtc'].get_property(p2.name)))
def on_ice_connection_state(p1, p2):
if (client['webrtc'].get_property(p2.name)==1):
printwarn("ice changed to checking state")
elif (client['webrtc'].get_property(p2.name)==2):
printwarn("ice changed to connected state")