-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
publish.py
2036 lines (1757 loc) · 96.8 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
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
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
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 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 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 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)
class WebRTCClient:
def __init__(self, params):
self.pipeline = params.pipeline
self.conn = None
self.pipe = None
self.h264 = params.h264
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.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 = None
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.aom = params.aom
self.av1 = params.av1
try:
if self.password:
parsed_url = urlparse(self.hostname)
hostname_parts = parsed_url.hostname.split(".")
result = ".".join(hostname_parts[-2:])
self.hashcode = generateHash(self.password+result, 6)
except Exception as E:
print(E)
if self.save_file:
self.pipe = Gst.parse_launch(self.pipeline)
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_name:
msg = json.dumps({"request":"joinroom","roomid":self.room_name})
await self.conn.send(msg)
printwout("joining room")
elif self.streamin:
msg = json.dumps({"request":"play","streamID":self.streamin+self.hashcode})
await self.conn.send(msg)
printwout("requesting stream")
else:
msg = json.dumps({"request":"seed","streamID":self.stream_id+self.hashcode})
await self.conn.send(msg)
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']]
msg = json.dumps(msg)
if client and client['send_channel']:
try:
client['send_channel'].emit('send-string', msg)
printout("a message was sent via datachannels: "+msg[:20])
except Exception as e:
loop = asyncio.new_event_loop()
loop.run_until_complete(self.conn.send(msg))
printwout("a message was sent via websockets 2: "+msg[:20])
else:
loop = asyncio.new_event_loop()
loop.run_until_complete(self.conn.send(msg))
printwout("a message was sent via websockets 1: "+msg[:20])
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")
elif (client['webrtc'].get_property(p2.name)==3):
printwarn("ice changed to completed state")
elif (client['webrtc'].get_property(p2.name)>3):
printc("ice changed to state +4","FC2")
def on_connection_state(p1, p2):
print("on_connection_state")
if (client['webrtc'].get_property(p2.name)==2): # connected
print("PEER CONNECTION ACTIVE")
promise = Gst.Promise.new_with_change_func(on_stats, client['webrtc'], None) # check stats
client['webrtc'].emit('get-stats', None, promise)
if not self.streamin and not client['send_channel']:
channel = client['webrtc'].emit('create-data-channel', 'sendChannel', None)
on_data_channel(client['webrtc'], channel)
if client['timer'] == None:
client['ping'] = 0
client['timer'] = threading.Timer(3, pingTimer)
client['timer'].start()
self.clients[client["UUID"]] = client
elif (client['webrtc'].get_property(p2.name)>=4): # closed/failed , but this won't work unless Gstreamer / LibNice support it -- which isn't the case in most versions.
print("PEER CONNECTION DISCONNECTED")
self.stop_pipeline(client['UUID'])
else:
print("PEER CONNECTION STATE {}".format(client['webrtc'].get_property(p2.name)))
def print_trans(p1,p2):
print("trans: {}".format(client['webrtc'].get_property(p2.name)))
def pingTimer():
if not client['send_channel']:
client['timer'] = threading.Timer(3, pingTimer)
client['timer'].start()
print("data channel not setup yet")
return
if "ping" not in client:
client['ping'] = 0
if client['ping'] < 10:
client['ping'] += 1
self.clients[client["UUID"]] = client
try:
client['send_channel'].emit('send-string', '{"ping":"'+str(time.time())+'"}')
printout("PINGED")
except Exception as E:
print(E)
print("PING FAILED")
client['timer'] = threading.Timer(3, pingTimer)
client['timer'].start()
promise = Gst.Promise.new_with_change_func(on_stats, client['webrtc'], None) # check stats
client['webrtc'].emit('get-stats', None, promise)
else:
printc("NO HEARTBEAT", "F44")
self.stop_pipeline(client['UUID'])
def on_data_channel(webrtc, channel):
print(" --------- ON DATA CHANNEL")
if channel is None:
print('DATA CHANNEL: NOT AVAILABLE')
return
else:
print('DATA CHANNEL SETUP')
channel.connect('on-open', on_data_channel_open)
channel.connect('on-error', on_data_channel_error)
channel.connect('on-close', on_data_channel_close)
channel.connect('on-message-string', on_data_channel_message)
def on_data_channel_error(arg1, arg2):
printc('DATA CHANNEL: ERROR', "F44")
def on_data_channel_open(channel):
printc('DATA CHANNEL: OPENED', "06F")
client['send_channel'] = channel
self.clients[client["UUID"]] = client
if self.streamin:
if self.noaudio:
msg = {"audio":False, "video":True, "UUID": client["UUID"]} ## You must edit the SDP instead if you want to force a particular codec
else:
msg = {"audio":True, "video":True, "UUID": client["UUID"]} ## You must edit the SDP instead if you want to force a particular codec
self.sendMessage(msg)
elif self.midi:
msg = {"audio":False, "video":False, "allowmidi":True, "UUID": client["UUID"]} ## You must edit the SDP instead if you want to force a particular codec
self.sendMessage(msg)
elif self.rotate:
msg = {"info":{"rotate_video":self.rotate}, "UUID": client["UUID"]}
self.sendMessage(msg)
def on_data_channel_close(channel):
printc('DATA CHANNEL: CLOSE', "F44")
def on_data_channel_message(channel, msg_raw):
try:
msg = json.loads(msg_raw)
except:
printin("DID NOT GET JSON")
return
if 'candidates' in msg:
printin("INBOUND ICE BUNDLE - DC")
for ice in msg['candidates']:
self.handle_sdp_ice(ice, client["UUID"])
elif 'candidate' in msg:
printin("INBOUND ICE SINGLE - DC")
self.handle_sdp_ice(msg, client["UUID"])
elif 'pong' in msg: # Supported in v19 of VDO.Ninja
printin('PONG')
client['ping'] = 0
self.clients[client["UUID"]] = client
elif 'bye' in msg: ## v19 of VDO.Ninja
printin("PEER INTENTIONALLY HUNG UP")
elif 'description' in msg:
printin("INCOMING SDP - DC")
if msg['description']['type'] == "offer":
self.handle_offer(msg['description'], client['UUID'])
elif 'midi' in msg:
printin(msg)
vdo2midi(msg['midi'])
elif 'bitrate' in msg:
printin(msg)
if client['encoder'] and msg['bitrate']:
print("Trying to change bitrate...")
if self.aom:
print("Aom doesn't support dynamic bitrates currently")
pass
else:
client['encoder'].set_property('bitrate', int(msg['bitrate'])*1000)
else:
printin("MISC DC DATA")
return
def vdo2midi(midi):
try:
if self.midiout == None:
self.midiout = rtmidi.MidiOut()
new_out_port = self.midiout.get_ports() # a bit inefficient, but safe
if new_out_port != self.midiout_ports:
print("New MIDI Out device(s) initializing...")
self.midiout_ports = new_out_port
try:
self.midiout.close_port()
except:
pass
for i in range(len(self.midiout_ports)):
if "Midi Through" in self.midiout_ports[i]:
continue
break
if i < len(self.midiout_ports):
self.midiout.open_port(i)
print(i) ## midi output device
else:
return ## no MIDI out found; skipping
self.midiout.send_message(midi['d'])
except Exception as E:
print(E)
def sendMIDI(data, template):
if data:
template['midi']['d'] = data[0];
data = json.dumps(template)
for client in self.clients:
if self.clients[client]['send_channel']:
try:
self.clients[client]['send_channel'].emit('send-string', data)
except:
pass
def midi2vdo(midi):
in_ports = None
self.midiin = rtmidi.MidiIn()
while True:
in_ports_new = self.midiin.get_ports()
if in_ports_new != in_ports:
in_ports = in_ports_new
if self.midiin:
print("New MIDI Input device(s) initializing...")
try:
self.midiin.close_port()
except:
pass
while True:
print(in_ports)
for i in range(len(in_ports)):
if "Midi Through" in in_ports[i]:
continue
break
if i < len(in_ports):
self.midiin.open_port(i)
print(i) ## midi input device
break
else:
time.sleep(0.5)
in_ports = self.midiin.get_ports()
template = {}
template['midi'] = {}
template['midi']['d'] = []
if self.puuid:
template['from'] = self.puuid
self.midiin.cancel_callback()
self.midiin.set_callback(sendMIDI, template)
else:
time.sleep(4)
def on_stats(promise, abin, data):
promise.wait()
stats = promise.get_reply()
stats = stats.to_string()
stats = stats.replace("\\", "")
stats = stats.split("fraction-lost=(double)")
if (len(stats)>1):
stats = stats[1].split(",")[0]
print("Packet loss:"+stats)
if " vp8enc " in self.pipeline: # doesn't support dynamic bitrates? not sure the property to use at least
return
elif " av1enc " in self.pipeline: # seg-fault if I try to change it currently
return
stats = float(stats)
if (stats>0.01) and not self.noqos:
print("Trying to reduce change bitrate...")
bitrate = self.bitrate*0.9
if bitrate < self.max_bitrate*0.2:
bitrate = self.max_bitrate*0.2
elif bitrate > self.max_bitrate*0.8:
bitrate = self.bitrate*0.9
self.bitrate = bitrate
print(str(bitrate))
try:
if self.aom:
client['encoder'].set_property('target-bitrate', int(bitrate)) # line not active due to 'elif " av1enc " in self.pipeline:' line
elif client['encoder']:
client['encoder'].set_property('bitrate', int(bitrate*1000))
elif client['encoder1']:
client['encoder1'].set_property('bitrate', int(bitrate))
elif client['encoder2']:
pass
except Exception as E:
print(E)
elif (stats<0.003) and not self.noqos:
print("Trying to increase change bitrate...")
bitrate = self.bitrate*1.05
if bitrate>self.max_bitrate:
bitrate = self.max_bitrate
elif bitrate*2<self.max_bitrate:
bitrate = self.bitrate*1.05
self.bitrate = bitrate
print(str(bitrate))
try:
if self.aom:
client['encoder'].set_property('target-bitrate', int(bitrate)) # line not active due to 'elif " av1enc " in self.pipeline:' line
elif client['encoder']:
client['encoder'].set_property('bitrate', int(bitrate*1000))
elif client['encoder1']:
client['encoder1'].set_property('bitrate', int(bitrate))
elif client['encoder2']:
pass
except Exception as E:
print(E)
def new_sample(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:
print(E)
self.processing = False
return False
def on_frame_probe(pad, info):
buf = info.get_buffer()
print(f'[{buf.pts / Gst.SECOND:6.2f}]')
return Gst.PadProbeReturn.OK
def on_incoming_stream( _, pad):
print("ON INCOMING AUDIO OR VIDEO STREAM")
try:
if Gst.PadDirection.SRC != pad.direction:
print("pad direction wrong?")
return
caps = pad.get_current_caps()
name = caps.to_string()
print(name)
if "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:
print("NDI OUT")
if "VP8" in name:
out = Gst.parse_bin_from_description("queue ! rtpvp8depay ! decodebin ! videoconvert ! queue ! video/x-raw,format=UYVY ! ndisinkcombiner name=mux1 ! ndisink ndi-name='" + self.streamin + "'", True)
elif "H264" in name:
out = Gst.parse_bin_from_description("queue ! rtph264depay ! h264parse ! queue max-size-buffers=0 max-size-time=0 ! decodebin ! queue max-size-buffers=0 max-size-time=0 ! videoconvert ! queue max-size-buffers=0 max-size-time=0 ! video/x-raw,format=UYVY ! ndisinkcombiner name=mux1 ! queue ! ndisink ndi-name='" + self.streamin + "'", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
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")
if "VP8" in name:
out = Gst.parse_bin_from_description(
"queue ! rtpvp8depay ! decodebin ! queue max-size-buffers=0 max-size-time=0 ! videoconvert ! queue max-size-buffers=0 max-size-time=0 ! video/x-raw,format=BGR ! fdsink", True)
elif "H264" in name:
out = Gst.parse_bin_from_description(
"queue ! rtph264depay ! h264parse ! openh264dec ! videoconvert ! video/x-raw,format=BGR ! queue max-size-buffers=0 max-size-time=0 ! fdsink", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
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 ! filesink name=filesinkvideo sync=false location="+self.streamin+"_"+str(int(time.time()))+"_video.ts", True)
elif "H264" in name:
out = Gst.parse_bin_from_description("queue ! rtph264depay ! h264parse ! mpegtsmux name=mux1 ! queue ! filesink name=filesinkvideo sync=true location="+self.streamin+"_"+str(int(time.time()))+"_video.ts", 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", 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:
# if "OPUS" in name:
out = Gst.parse_bin_from_description("queue ! rtpopusdepay ! opusparse ! opusdec ! audioconvert ! audioresample ! audio/x-raw,format=S16LE,rate=48000 ! ndisink name=ndi-audio ndi-name='" + self.streamin + "'", True)
self.pipe.add(out)
out.sync_state_with_parent()
sink = out.get_static_pad('sink')
pad.link(sink)
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 ! filesink name=filesinkaudio sync=true location="+self.streamin+"_"+str(int(time.time()))+"_audio.ts", 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 =========")
print(E)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
print("creating a new webrtc bin")
started = True
if not self.pipe:
print("loading pipe")
if self.streamin:
self.pipe = Gst.Pipeline.new('decode-pipeline') ## decode or capture
elif len(self.pipeline)<=1:
self.pipe = Gst.Pipeline.new('data-only-pipeline')
else:
print(self.pipeline)
self.pipe = Gst.parse_launch(self.pipeline)
print(self.pipe)
started = False
client['webrtc'] = self.pipe.get_by_name('sendrecv')
client['qv'] = None
client['qa'] = None
client['encoder'] = False
client['encoder1'] = False
client['encoder2'] = False
try:
client['encoder'] = self.pipe.get_by_name('encoder')
except:
try:
client['encoder1'] = self.pipe.get_by_name('encoder1')
except:
try:
client['encoder2'] = self.pipe.get_by_name('encoder2')
except:
pass
if self.streamin:
client['webrtc'] = Gst.ElementFactory.make("webrtcbin", client['UUID'])
client['webrtc'].set_property('bundle-policy', "max-bundle")
client['webrtc'].set_property('stun-server', "stun://stun4.l.google.com:19302") ## older versions of gstreamer might break with this
client['webrtc'].set_property('turn-server', 'turn://vdoninja:IchBinSteveDerNinja@www.turn.vdo.ninja:3478') # temporarily hard-coded
try:
client['webrtc'].set_property('latency', self.buffer)
client['webrtc'].set_property('async-handling', True)
except:
pass
self.pipe.add(client['webrtc'])
if self.h264:
direction = GstWebRTC.WebRTCRTPTransceiverDirection.RECVONLY
caps = Gst.caps_from_string("application/x-rtp,media=video,encoding-name=H264,payload=102,clock-rate=90000,packetization-mode=(string)1");
tcvr = client['webrtc'].emit('add-transceiver', direction, caps)
if Gst.version().minor > 18:
tcvr.set_property("codec-preferences",caps) ## supported as of around June 2021 in gstreamer for answer side?
elif (not self.multiviewer) and client['webrtc']:
pass
else:
client['webrtc'] = Gst.ElementFactory.make("webrtcbin", client['UUID'])
client['webrtc'].set_property('bundle-policy', 'max-bundle')
client['webrtc'].set_property('stun-server', "stun://stun4.l.google.com:19302") ## older versions of gstreamer might break with this
client['webrtc'].set_property('turn-server', 'turn://vdoninja:IchBinSteveDerNinja@www.turn.vdo.ninja:3478') # temporarily hard-coded
try:
client['webrtc'].set_property('latency', self.buffer)
client['webrtc'].set_property('async-handling', True)
except:
pass
self.pipe.add(client['webrtc'])
atee = self.pipe.get_by_name('audiotee')
vtee = self.pipe.get_by_name('videotee')
if vtee is not None:
qv = Gst.ElementFactory.make('queue', f"qv-{client['UUID']}")
self.pipe.add(qv)
if not Gst.Element.link(vtee, qv):
return
if not Gst.Element.link(qv, client['webrtc']):
return
if qv is not None: qv.sync_state_with_parent()
client['qv'] = qv
if atee is not None:
qa = Gst.ElementFactory.make('queue', f"qa-{client['UUID']}")
self.pipe.add(qa)
if not Gst.Element.link(atee, qa):
return
if not Gst.Element.link(qa, client['webrtc']):
return
if qa is not None: qa.sync_state_with_parent()
client['qa'] = qa
if self.midi and (self.midi_thread == None):
self.midi_thread = threading.Thread(target=midi2vdo, args=(self.midi,))
self.midi_thread.start()
print(self.midi_thread)
print("MIDI THREAD STARTED")
try:
client['webrtc'].connect('notify::ice-connection-state', on_ice_connection_state)
client['webrtc'].connect('notify::connection-state', on_connection_state)
client['webrtc'].connect('notify::signaling-state', on_signaling_state)
except Exception as e:
print(e)
pass
if self.streamin:
client['webrtc'].connect('pad-added', on_incoming_stream)
client['webrtc'].connect('on-ice-candidate', send_ice_remote_candidate_message)
client['webrtc'].connect('on-data-channel', on_data_channel)
else:
client['webrtc'].connect('on-ice-candidate', send_ice_local_candidate_message)
client['webrtc'].connect('on-negotiation-needed', on_negotiation_needed)
client['webrtc'].connect('on-new-transceiver', on_new_tranceiver)
try:
if not self.streamin:
trans = client['webrtc'].emit("get-transceiver",0)
if trans is not None:
try:
if not self.nored:
trans.set_property("fec-type", GstWebRTC.WebRTCFECType.ULP_RED)
print("FEC ENABLED")
except:
pass
trans.set_property("do-nack", True)
print("SEND NACKS ENABLED")
except Exception as E:
print(E)
if not started and self.pipe.get_state(0)[1] is not Gst.State.PLAYING:
self.pipe.set_state(Gst.State.PLAYING)
client['webrtc'].sync_state_with_parent()
if not self.streamin and not client['send_channel']:
channel = client['webrtc'].emit('create-data-channel', 'sendChannel', None)
on_data_channel(client['webrtc'], channel)
self.clients[client["UUID"]] = client
def handle_sdp_ice(self, msg, UUID):
client = self.clients[UUID]
if not client or not client['webrtc']:
print("! CLIENT NOT FOUND OR INVALID")
return
if 'sdp' in msg:
print("INCOMING ANSWER SDP TYPE: "+msg['type'])
assert(msg['type'] == 'answer')
sdp = msg['sdp']
res, sdpmsg = GstSdp.SDPMessage.new()
GstSdp.sdp_message_parse_buffer(bytes(sdp.encode()), sdpmsg)
answer = GstWebRTC.WebRTCSessionDescription.new(GstWebRTC.WebRTCSDPType.ANSWER, sdpmsg)
promise = Gst.Promise.new()
client['webrtc'].emit('set-remote-description', answer, promise)
promise.interrupt()
elif 'candidate' in msg:
print(" ~ HANDLING INBOUND ICE")
candidate = msg['candidate']
sdpmlineindex = msg['sdpMLineIndex']
client['webrtc'].emit('add-ice-candidate', sdpmlineindex, candidate)