421 lines
21 KiB
Python
421 lines
21 KiB
Python
#!/usr/bin/env python3
|
|
# JumPHP WebRTC sidecar: a native WebRTC peer (GStreamer webrtcbin) driven by JSON lines on stdin / stdout.
|
|
# Used by jumphp/webrtc on the desktop (JumPHP\WebRtc\GstBackend) and by the JumPHP IDE's "screen on a phone" (VNC-like) mode.
|
|
# Needs: python3-gi, GStreamer >= 1.20 with webrtcbin (plugins-bad) + nice (libnice) + an H.264 encoder (x264, VA, NVENC), X11 for the screen.
|
|
# Protocol (one JSON object per line; docs: extensions/webrtc/doc/sidecar.md):
|
|
# in : {"op":"peer","id":"p","stun":"stun://host:port","turn":"turn://user:pass@host:port"} ("turns": [several])
|
|
# {"op":"screen","id":"p","fps":60,"kbps":8000,"width":1920,"display":":0","input":true,"encoder":"auto"}
|
|
# {"op":"channel","id":"p","label":"data","ordered":true}
|
|
# {"op":"offer","id":"p"} | {"op":"remote","id":"p","type":"answer|offer","sdp":"..."} | {"op":"ice","id":"p","candidate":"...","mline":0}
|
|
# {"op":"send","id":"p","label":"data","text":"..."} | {..."b64":"..."} | {"op":"kbps","id":"p","kbps":4000} | {"op":"close","id":"p"} | {"op":"quit"}
|
|
# out: {"ev":"ready","version":1,"encoders":[...]} {"ev":"offer"|"answer","id","sdp"} {"ev":"ice","id","candidate","mline"}
|
|
# {"ev":"state","id","state"} {"ev":"open"|"close","id","label"} {"ev":"message","id","label","text"|"b64"} {"ev":"error","id","message"}
|
|
import base64, ctypes, ctypes.util, json, os, sys, threading
|
|
|
|
import gi
|
|
gi.require_version('Gst', '1.0')
|
|
gi.require_version('GstWebRTC', '1.0')
|
|
gi.require_version('GstSdp', '1.0')
|
|
gi.require_version('GstVideo', '1.0')
|
|
from gi.repository import GLib, Gst, GstSdp, GstVideo, GstWebRTC # noqa: E402
|
|
|
|
Gst.init(None)
|
|
_out = threading.Lock()
|
|
|
|
|
|
def emit(ev, **kw):
|
|
kw['ev'] = ev
|
|
line = json.dumps(kw, separators=(',', ':'))
|
|
with _out:
|
|
sys.stdout.write(line + '\n')
|
|
sys.stdout.flush()
|
|
|
|
|
|
# --- encoders: the first one of AUTO_ORDER that works on this machine -------------------------------------------------
|
|
ENCODERS = {
|
|
'nvenc': 'nvh264enc preset=low-latency-hq rc-mode=cbr bitrate={kbps} gop-size={gop} zerolatency=true bframes=0 name=enc',
|
|
'va': 'vah264lpenc rate-control=cbr bitrate={kbps} key-int-max={gop} b-frames=0 target-usage=7 name=enc',
|
|
'va2': 'vah264enc rate-control=cbr bitrate={kbps} key-int-max={gop} b-frames=0 target-usage=7 name=enc',
|
|
'vaapi': 'vaapih264enc rate-control=cbr bitrate={kbps} keyframe-period={gop} max-bframes=0 tune=low-power name=enc',
|
|
'x264': 'x264enc tune=zerolatency speed-preset=ultrafast bitrate={kbps} key-int-max={gop} bframes=0 sliced-threads=false threads=4 name=enc',
|
|
'openh264': 'openh264enc bitrate={bps} gop-size={gop} complexity=low rate-control=bitrate name=enc',
|
|
}
|
|
PRE = {'nvenc': 'videoconvert ! video/x-raw,format=NV12', 'va': 'videoconvert ! video/x-raw,format=NV12', 'va2': 'videoconvert ! video/x-raw,format=NV12',
|
|
'vaapi': 'videoconvert ! video/x-raw,format=NV12', 'x264': 'videoconvert ! video/x-raw,format=I420', 'openh264': 'videoconvert ! video/x-raw,format=I420'}
|
|
|
|
|
|
def enc_desc(name, kbps, gop):
|
|
return ENCODERS[name].format(kbps=kbps, bps=kbps * 1000, gop=gop)
|
|
|
|
|
|
def encoder_works(name):
|
|
try:
|
|
p = Gst.parse_launch('videotestsrc num-buffers=3 ! video/x-raw,width=320,height=240 ! %s ! %s ! h264parse ! fakesink' % (PRE[name], enc_desc(name, 1000, 30)))
|
|
except GLib.Error:
|
|
return False
|
|
p.set_state(Gst.State.PLAYING)
|
|
msg = p.get_bus().timed_pop_filtered(4 * Gst.SECOND, Gst.MessageType.EOS | Gst.MessageType.ERROR)
|
|
p.set_state(Gst.State.NULL)
|
|
return msg is not None and msg.type == Gst.MessageType.EOS
|
|
|
|
|
|
# 'auto' = the GPU first (NVENC, VA-API: almost no CPU, ~2 ms an image), then x264 zero-latency, then OpenH264
|
|
AUTO_ORDER = ['nvenc', 'va', 'va2', 'vaapi', 'x264', 'openh264']
|
|
AVAILABLE = [n for n in AUTO_ORDER if Gst.ElementFactory.find(ENCODERS[n].split()[0]) and encoder_works(n)]
|
|
|
|
|
|
# --- input (XTest): absolute / relative mouse, buttons, wheel, keys, text --------------------------------------------------
|
|
class XInput:
|
|
def __init__(self, display):
|
|
x11 = ctypes.cdll.LoadLibrary(ctypes.util.find_library('X11') or 'libX11.so.6')
|
|
xt = ctypes.cdll.LoadLibrary(ctypes.util.find_library('Xtst') or 'libXtst.so.6')
|
|
x11.XOpenDisplay.restype = ctypes.c_void_p
|
|
x11.XOpenDisplay.argtypes = [ctypes.c_char_p]
|
|
x11.XStringToKeysym.restype = ctypes.c_ulong
|
|
x11.XStringToKeysym.argtypes = [ctypes.c_char_p]
|
|
x11.XKeysymToKeycode.restype = ctypes.c_ubyte
|
|
x11.XKeysymToKeycode.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
|
|
x11.XKeycodeToKeysym.restype = ctypes.c_ulong
|
|
x11.XKeycodeToKeysym.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int]
|
|
for f in ('XFlush', 'XDefaultScreen'):
|
|
getattr(x11, f).argtypes = [ctypes.c_void_p]
|
|
x11.XDisplayWidth.argtypes = x11.XDisplayHeight.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
|
x11.XDefaultRootWindow.restype = ctypes.c_ulong
|
|
x11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
|
|
x11.XChangeKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]
|
|
x11.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
|
|
x11.XQueryPointer.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + [ctypes.POINTER(ctypes.c_ulong)] * 2 + [ctypes.POINTER(ctypes.c_int)] * 4 + [ctypes.POINTER(ctypes.c_uint)]
|
|
xt.XTestFakeMotionEvent.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_ulong]
|
|
xt.XTestFakeButtonEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong]
|
|
xt.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong]
|
|
self.x, self.t = x11, xt
|
|
self.d = x11.XOpenDisplay(display.encode() if display else None)
|
|
if not self.d:
|
|
raise RuntimeError('cannot open the X display %s' % display)
|
|
self.screen = x11.XDefaultScreen(self.d)
|
|
self.w, self.h = x11.XDisplayWidth(self.d, self.screen), x11.XDisplayHeight(self.d, self.screen)
|
|
lo, hi = ctypes.c_int(), ctypes.c_int()
|
|
x11.XDisplayKeycodes(self.d, ctypes.byref(lo), ctypes.byref(hi))
|
|
self.spare = next((k for k in range(hi.value, lo.value, -1) if x11.XKeycodeToKeysym(self.d, k, 0) == 0), 0)
|
|
self.shift = x11.XKeysymToKeycode(self.d, x11.XStringToKeysym(b'Shift_L'))
|
|
|
|
def pointer(self):
|
|
r, c = ctypes.c_ulong(), ctypes.c_ulong()
|
|
rx, ry, wx, wy, m = ctypes.c_int(), ctypes.c_int(), ctypes.c_int(), ctypes.c_int(), ctypes.c_uint()
|
|
self.x.XQueryPointer(self.d, self.x.XDefaultRootWindow(self.d), ctypes.byref(r), ctypes.byref(c), ctypes.byref(rx), ctypes.byref(ry), ctypes.byref(wx), ctypes.byref(wy), ctypes.byref(m))
|
|
return rx.value, ry.value
|
|
|
|
def move(self, x, y):
|
|
self.t.XTestFakeMotionEvent(self.d, self.screen, max(0, min(self.w - 1, int(x))), max(0, min(self.h - 1, int(y))), 0)
|
|
|
|
def keysym(self, name):
|
|
if len(name) == 1:
|
|
cp = ord(name)
|
|
return cp if 0x20 <= cp <= 0x7e or 0xa0 <= cp <= 0xff else 0x1000000 + cp
|
|
return self.x.XStringToKeysym(name.encode())
|
|
|
|
def key(self, sym, down):
|
|
code = self.x.XKeysymToKeycode(self.d, sym)
|
|
if code:
|
|
self.t.XTestFakeKeyEvent(self.d, code, 1 if down else 0, 0)
|
|
return
|
|
if down and self.spare: # not on the keyboard (é on a US layout, emoji...): put it on a spare keycode for this press
|
|
arr = (ctypes.c_ulong * 2)(sym, sym)
|
|
self.x.XChangeKeyboardMapping(self.d, self.spare, 2, arr, 1)
|
|
self.x.XFlush(self.d)
|
|
self.t.XTestFakeKeyEvent(self.d, self.spare, 1, 0)
|
|
self.t.XTestFakeKeyEvent(self.d, self.spare, 0, 0)
|
|
|
|
def char(self, ch):
|
|
sym = self.keysym(ch)
|
|
code = self.x.XKeysymToKeycode(self.d, sym)
|
|
shifted = code and self.x.XKeycodeToKeysym(self.d, code, 0) != sym and self.x.XKeycodeToKeysym(self.d, code, 1) == sym
|
|
if shifted:
|
|
self.t.XTestFakeKeyEvent(self.d, self.shift, 1, 0)
|
|
self.key(sym, True)
|
|
if code:
|
|
self.key(sym, False)
|
|
if shifted:
|
|
self.t.XTestFakeKeyEvent(self.d, self.shift, 0, 0)
|
|
|
|
def handle(self, m):
|
|
t = m.get('t')
|
|
if t == 'm': # absolute, 0..1 of the screen
|
|
self.move(float(m['x']) * self.w, float(m['y']) * self.h)
|
|
elif t == 'r': # relative, pixels of the screen
|
|
x, y = self.pointer()
|
|
self.move(x + float(m['dx']), y + float(m['dy']))
|
|
elif t == 'b': # button 1 left, 2 middle, 3 right; d = down
|
|
if 'x' in m:
|
|
self.move(float(m['x']) * self.w, float(m['y']) * self.h)
|
|
self.t.XTestFakeButtonEvent(self.d, int(m['b']), 1 if m.get('d') else 0, 0)
|
|
elif t == 'w': # wheel: dy > 0 down, dx > 0 right, in notches
|
|
for axis, (neg, pos) in (('dy', (4, 5)), ('dx', (6, 7))):
|
|
n = int(m.get(axis, 0))
|
|
for _ in range(min(abs(n), 20)):
|
|
b = pos if n > 0 else neg
|
|
self.t.XTestFakeButtonEvent(self.d, b, 1, 0)
|
|
self.t.XTestFakeButtonEvent(self.d, b, 0, 0)
|
|
elif t == 'k': # a key by X keysym name (Return, Escape, Control_L, F5, a...), d = down
|
|
self.key(self.keysym(str(m['key'])), bool(m.get('d')))
|
|
elif t == 'txt': # text typed as is
|
|
for ch in str(m.get('s', ''))[:2000]:
|
|
if ch == '\n':
|
|
self.key(self.keysym('Return'), True); self.key(self.keysym('Return'), False)
|
|
else:
|
|
self.char(ch)
|
|
self.x.XFlush(self.d)
|
|
|
|
|
|
# --- peers -----------------------------------------------------------------------------------------------------------------
|
|
class Peer:
|
|
def __init__(self, pid, opts):
|
|
self.id, self.channels, self.input, self.screen = pid, {}, None, None
|
|
self.pipe = Gst.Pipeline.new('peer-' + pid)
|
|
self.rtc = Gst.ElementFactory.make('webrtcbin', 'rtc')
|
|
self.rtc.set_property('bundle-policy', GstWebRTC.WebRTCBundlePolicy.MAX_BUNDLE)
|
|
self.rtc.set_property('latency', 0)
|
|
if opts.get('stun'):
|
|
self.rtc.set_property('stun-server', opts['stun'])
|
|
for turn in (opts.get('turns') or ([opts['turn']] if opts.get('turn') else [])):
|
|
self.rtc.emit('add-turn-server', turn)
|
|
self.pipe.add(self.rtc)
|
|
self.rtc.connect('on-ice-candidate', lambda _r, ml, c: emit('ice', id=self.id, candidate=c, mline=ml))
|
|
self.rtc.connect('on-data-channel', lambda _r, ch: self.wire(ch))
|
|
self.want_offer = self.negotiable = self.has_remote = False
|
|
self.early_ice = [] # an offer is made once webrtcbin says it is ready for one
|
|
self.rtc.connect('on-negotiation-needed', lambda _r: self.negotiation_needed())
|
|
self.rtc.connect('notify::connection-state', lambda r, _p: emit('state', id=self.id, state=r.get_property('connection-state').value_nick))
|
|
bus = self.pipe.get_bus()
|
|
bus.add_signal_watch()
|
|
bus.connect('message::error', lambda _b, m: emit('error', id=self.id, message=m.parse_error()[0].message))
|
|
self.pipe.set_state(Gst.State.PLAYING)
|
|
|
|
def add_screen(self, o):
|
|
enc = o.get('encoder', 'auto')
|
|
enc = enc if enc in AVAILABLE else (AVAILABLE[0] if AVAILABLE else None)
|
|
if not enc:
|
|
raise RuntimeError('no H.264 encoder (install gstreamer1.0-plugins-ugly for x264)')
|
|
fps, kbps = int(o.get('fps', 60)), int(o.get('kbps', 6000))
|
|
display = o.get('display') or os.environ.get('DISPLAY', ':0')
|
|
scale = ''
|
|
if int(o.get('width', 0)) > 0:
|
|
scale = 'videoscale method=bilinear ! video/x-raw,width=%d,pixel-aspect-ratio=1/1 ! ' % int(o['width'])
|
|
desc = ('ximagesrc display-name=%s use-damage=false show-pointer=true ! video/x-raw,framerate=%d/1 ! queue leaky=downstream max-size-buffers=1 ! '
|
|
'%s%s ! %s ! video/x-h264,profile=constrained-baseline ! h264parse config-interval=-1 ! video/x-h264,stream-format=byte-stream,alignment=au ! '
|
|
'rtph264pay config-interval=-1 aggregate-mode=zero-latency mtu=1200 ! capsfilter caps="application/x-rtp,media=video,encoding-name=H264,payload=96,clock-rate=90000"') % (
|
|
display, fps, scale, PRE[enc], enc_desc(enc, kbps, fps * 2))
|
|
try:
|
|
bin_ = Gst.parse_bin_from_description(desc, True)
|
|
except GLib.Error: # some encoders refuse the baseline caps: let them pick
|
|
bin_ = Gst.parse_bin_from_description(desc.replace(' ! video/x-h264,profile=constrained-baseline', ''), True)
|
|
caps = Gst.Caps.from_string('application/x-rtp,media=video,encoding-name=H264,payload=96,clock-rate=90000,'
|
|
'packetization-mode=(string)1,profile-level-id=(string)42e01f,level-asymmetry-allowed=(string)1')
|
|
self.pipe.add(bin_)
|
|
sink = self.rtc.request_pad(self.rtc.get_pad_template('sink_%u'), None, caps)
|
|
sink.get_property('transceiver').set_property('direction', GstWebRTC.WebRTCRTPTransceiverDirection.SENDONLY)
|
|
bin_.get_static_pad('src').link(sink)
|
|
bin_.sync_state_with_parent()
|
|
self.screen = bin_
|
|
self.encoder = enc
|
|
if o.get('input', True):
|
|
self.input = XInput(display)
|
|
self.add_channel({'label': 'input', 'ordered': True})
|
|
return {'encoder': enc, 'width': self.input.w if self.input else 0, 'height': self.input.h if self.input else 0}
|
|
|
|
def set_kbps(self, kbps):
|
|
enc = self.screen and self.screen.get_by_name('enc')
|
|
if enc:
|
|
for prop, val in (('bitrate', int(kbps)),):
|
|
try:
|
|
enc.set_property(prop, val * (1000 if 'openh264' in enc.get_factory().get_name() else 1))
|
|
except TypeError:
|
|
pass
|
|
|
|
def keyframe(self):
|
|
"""A new IDR frame now (the viewer decoded nothing yet, or lost the stream)."""
|
|
enc = self.screen and self.screen.get_by_name('enc')
|
|
if enc:
|
|
enc.get_static_pad('src').send_event(GstVideo.video_event_new_upstream_force_key_unit(Gst.CLOCK_TIME_NONE, True, 0))
|
|
|
|
def add_channel(self, o):
|
|
opts = Gst.Structure.new_from_string('o,ordered=%s' % ('true' if o.get('ordered', True) else 'false'))
|
|
if 'retransmits' in o:
|
|
opts.set_value('max-retransmits', int(o['retransmits']))
|
|
ch = self.rtc.emit('create-data-channel', o.get('label', 'data'), opts)
|
|
self.wire(ch)
|
|
|
|
def wire(self, ch):
|
|
label = ch.get_property('label')
|
|
self.channels[label] = ch
|
|
ch.connect('on-open', lambda c: self.opened(label, c))
|
|
ch.connect('on-close', lambda _c: emit('close', id=self.id, label=label))
|
|
ch.connect('on-message-string', lambda _c, s: self.message(label, s))
|
|
ch.connect('on-message-data', lambda _c, b: emit('message', id=self.id, label=label, b64=base64.b64encode(b.get_data()).decode()))
|
|
|
|
def opened(self, label, ch):
|
|
emit('open', id=self.id, label=label)
|
|
if label == 'input' and self.input:
|
|
ch.emit('send-string', json.dumps({'t': 'size', 'w': self.input.w, 'h': self.input.h, 'encoder': self.encoder}))
|
|
|
|
def message(self, label, text):
|
|
if label == 'input' and self.input:
|
|
try:
|
|
m = json.loads(text)
|
|
if m.get('t') == 'ping':
|
|
self.channels['input'].emit('send-string', json.dumps({'t': 'pong', 'at': m.get('at')}))
|
|
elif m.get('t') == 'key':
|
|
self.keyframe()
|
|
elif m.get('t') == 'kbps':
|
|
self.set_kbps(max(300, min(50000, int(m.get('kbps', 4000)))))
|
|
else:
|
|
self.input.handle(m)
|
|
except Exception as e: # a bad event never kills the session
|
|
emit('error', id=self.id, message='input: %s' % e)
|
|
return
|
|
emit('message', id=self.id, label=label, text=text)
|
|
|
|
def negotiation_needed(self):
|
|
self.negotiable = True
|
|
if self.want_offer:
|
|
self.want_offer = False
|
|
self.create_offer()
|
|
|
|
def offer(self):
|
|
if self.negotiable:
|
|
self.create_offer()
|
|
else:
|
|
self.want_offer = True
|
|
|
|
def create_offer(self):
|
|
def done(promise, _):
|
|
promise.wait()
|
|
reply = promise.get_reply()
|
|
offer = reply.get_value('offer') if reply and reply.has_field('offer') else None
|
|
if offer is None:
|
|
emit('error', id=self.id, message='offer: %s' % (reply.to_string() if reply else 'no reply'))
|
|
return
|
|
self.rtc.emit('set-local-description', offer, Gst.Promise.new())
|
|
emit('offer', id=self.id, sdp=offer.sdp.as_text())
|
|
self.rtc.emit('create-offer', None, Gst.Promise.new_with_change_func(done, None))
|
|
|
|
def remote(self, kind, sdp):
|
|
ok, msg = GstSdp.SDPMessage.new_from_text(sdp)
|
|
t = GstWebRTC.WebRTCSDPType.ANSWER if kind == 'answer' else GstWebRTC.WebRTCSDPType.OFFER
|
|
desc = GstWebRTC.WebRTCSessionDescription.new(t, msg)
|
|
|
|
def answered(promise, _):
|
|
try:
|
|
promise.wait()
|
|
reply = promise.get_reply()
|
|
ans = reply.get_value('answer') if reply and reply.has_field('answer') else None
|
|
if ans is None:
|
|
emit('error', id=self.id, message='answer: %s' % (reply.to_string() if reply else 'no reply'))
|
|
return
|
|
self.rtc.emit('set-local-description', ans, Gst.Promise.new())
|
|
emit('answer', id=self.id, sdp=ans.sdp.as_text())
|
|
except Exception as e: # a GStreamer thread: never lost silently
|
|
emit('error', id=self.id, message='answer: %s' % e)
|
|
|
|
def remote_set(promise, _):
|
|
GLib.idle_add(self.remote_ready)
|
|
if kind == 'offer':
|
|
self.rtc.emit('create-answer', None, Gst.Promise.new_with_change_func(answered, None))
|
|
self.rtc.emit('set-remote-description', desc, Gst.Promise.new_with_change_func(remote_set, None))
|
|
|
|
def add_ice(self, candidate, mline):
|
|
"""Candidates that come before the remote description wait for it."""
|
|
if self.has_remote:
|
|
self.rtc.emit('add-ice-candidate', mline, candidate)
|
|
else:
|
|
self.early_ice.append((mline, candidate))
|
|
|
|
def remote_ready(self):
|
|
self.has_remote = True
|
|
for mline, candidate in self.early_ice:
|
|
self.rtc.emit('add-ice-candidate', mline, candidate)
|
|
self.early_ice = []
|
|
return False
|
|
|
|
def close(self):
|
|
self.pipe.set_state(Gst.State.NULL)
|
|
|
|
|
|
peers = {}
|
|
loop = GLib.MainLoop()
|
|
|
|
|
|
def command(m):
|
|
op, pid = m.get('op'), str(m.get('id', ''))
|
|
if op == 'quit':
|
|
for p in peers.values():
|
|
p.close()
|
|
loop.quit()
|
|
return
|
|
if op == 'peer':
|
|
if pid in peers:
|
|
peers.pop(pid).close()
|
|
peers[pid] = Peer(pid, m)
|
|
return
|
|
p = peers.get(pid)
|
|
if not p:
|
|
raise RuntimeError('unknown peer %s' % pid)
|
|
if op == 'screen':
|
|
emit('screen', id=pid, **p.add_screen(m))
|
|
elif op == 'channel':
|
|
p.add_channel(m)
|
|
elif op == 'offer':
|
|
p.offer()
|
|
elif op == 'remote':
|
|
p.remote(m.get('type', 'answer'), m['sdp'])
|
|
elif op == 'ice':
|
|
if m.get('candidate'):
|
|
p.add_ice(m['candidate'], int(m.get('mline', 0)))
|
|
elif op == 'send':
|
|
ch = p.channels.get(m.get('label', 'data'))
|
|
if ch:
|
|
if 'b64' in m:
|
|
ch.emit('send-data', GLib.Bytes.new(base64.b64decode(m['b64'])))
|
|
else:
|
|
ch.emit('send-string', str(m.get('text', '')))
|
|
elif op == 'kbps':
|
|
p.set_kbps(int(m.get('kbps', 4000)))
|
|
elif op == 'key':
|
|
p.keyframe()
|
|
elif op == 'close':
|
|
peers.pop(pid).close()
|
|
|
|
|
|
_pending = b''
|
|
|
|
|
|
def on_stdin(fd, cond):
|
|
"""Reads what arrived (os.read: a buffered readline would keep lines GLib never wakes us up for), one command per line."""
|
|
global _pending
|
|
try:
|
|
chunk = os.read(fd, 65536)
|
|
except OSError:
|
|
chunk = b''
|
|
if not chunk:
|
|
loop.quit()
|
|
return False
|
|
_pending += chunk
|
|
while b'\n' in _pending:
|
|
line, _pending = _pending.split(b'\n', 1)
|
|
if not line.strip():
|
|
continue
|
|
try:
|
|
command(json.loads(line))
|
|
except Exception as e:
|
|
emit('error', message=str(e))
|
|
return True
|
|
|
|
|
|
if __name__ == '__main__':
|
|
missing = [e for e in ('webrtcbin', 'nicesrc') if not Gst.ElementFactory.find(e)]
|
|
if missing:
|
|
emit('error', fatal=True, message='GStreamer elements missing: %s (install gstreamer1.0-plugins-bad and gstreamer1.0-nice)' % ', '.join(missing))
|
|
sys.exit(2)
|
|
GLib.io_add_watch(sys.stdin.fileno(), GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, on_stdin)
|
|
emit('ready', version=1, encoders=AVAILABLE, gstreamer=Gst.version_string())
|
|
loop.run()
|