dsh-codex-subscription 3.1.8 → 3.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +4 -4
- package/README.md +4 -4
- package/lib/client.js +253 -115
- package/lib/index.js +1486 -80
- package/native/README.md +90 -0
- package/native/linux-voice-helper.py +528 -0
- package/package.json +2 -1
package/native/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Native Linux voice component
|
|
2
|
+
|
|
3
|
+
`linux-voice-helper.py` is an independent Python/GI GStreamer process. The plugin
|
|
4
|
+
uses it only from a local Linux desktop window without browser WebRTC, after an
|
|
5
|
+
explicit microphone confirmation. A normal WebRTC browser keeps its existing
|
|
6
|
+
media path. No audio samples cross Python/JavaScript IPC, no dependencies are
|
|
7
|
+
installed automatically, and the helper never accepts account credentials.
|
|
8
|
+
|
|
9
|
+
The authenticated host keeps signaling, account access and conversation ownership.
|
|
10
|
+
The helper handles audio devices and WebRTC. A session-specific lease protects
|
|
11
|
+
controls; losing the window's heartbeat stops capture after ten seconds. Startup
|
|
12
|
+
cancellation, hangup, settings disable and host disposal release the component.
|
|
13
|
+
The existing speech gate uses native levels to interrupt playback and resumes
|
|
14
|
+
only after old output has drained. Probe opens no microphone or speaker.
|
|
15
|
+
|
|
16
|
+
Runtime prerequisites: Python GI with Gst/GstSdp/GstWebRTC 1.0 introspection,
|
|
17
|
+
libnice, Opus RTP plugins, PulseAudio source/sink plugins and webrtcdsp. PulseAudio
|
|
18
|
+
can be supplied by PipeWire's Pulse server. On Arch the media dependencies are
|
|
19
|
+
`python-gobject gst-python gstreamer gst-plugins-base gst-plugins-good
|
|
20
|
+
gst-plugins-bad libnice pipewire-pulse wireplumber`. `probe` reports missing
|
|
21
|
+
factories without constructing a pipeline or opening audio devices. If the
|
|
22
|
+
runtime is unavailable, continue the same conversation in a WebRTC browser.
|
|
23
|
+
|
|
24
|
+
One bounded JSON object per line (128 KiB), with `id` and **`type`**. Replies contain
|
|
25
|
+
the same id and `ok`. stdout is protocol only; stderr contains native diagnostics.
|
|
26
|
+
|
|
27
|
+
- `probe`: capabilities plus counters; safe before start and useful while active.
|
|
28
|
+
- `start`: requires `captureAllowed:true`; optional `inputDevice`/`outputDevice`
|
|
29
|
+
are Pulse device names, never pipeline fragments. `role` is `offerer` (default)
|
|
30
|
+
or `answerer`. Only one session per process; stop permits a fresh start.
|
|
31
|
+
- `remote`: `descriptionType:'offer'|'answer'`, `sdp`. The `offer` and `answer`
|
|
32
|
+
command types are aliases. Commands acknowledge description dispatch; connection
|
|
33
|
+
readiness is asynchronous. Local `offer`/`answer` events wait for complete ICE.
|
|
34
|
+
- `mute`, `outputMute`: require `muted:boolean`. Microphone mute silences the
|
|
35
|
+
encoder input while continuing silent RTP to preserve the receiver's clock;
|
|
36
|
+
already-buffered pre-mute packets are discarded. It does not revoke the previously permitted
|
|
37
|
+
native device capture. Assistant level is measured before output mute.
|
|
38
|
+
- `interrupt`: suppresses output through the bounded native renderer. RTP and decoder
|
|
39
|
+
keep draining. `resume` discards stale timestamped output and restores playback
|
|
40
|
+
only if `outputMute` is not active. Acknowledgements include monotonicNs.
|
|
41
|
+
- `send`: optional bounded `data` string for data-channel tests. Received text is
|
|
42
|
+
never echoed; `data` events contain only byte count.
|
|
43
|
+
- `stop`: sets the whole pipeline NULL and reports `closed` with counters. EOF,
|
|
44
|
+
SIGINT/SIGTERM and detected parent death also stop and exit.
|
|
45
|
+
|
|
46
|
+
Events: `offer`/`answer` with SDP; `state` (WebRTC states or data-channel-open);
|
|
47
|
+
`level` with linear RMS mic/assistant; `error`; `closed`; optional `data` byte count.
|
|
48
|
+
SDP itself contains ICE credentials: the caller must keep SDP out of shared logs.
|
|
49
|
+
|
|
50
|
+
Both directions use 48 kHz mono S16LE. The echo probe is created before the DSP
|
|
51
|
+
and resides in the same top-level pipeline, after output volume/mute and directly
|
|
52
|
+
before pulsesink. Speaker output is native, never a browser AudioContext. A Pulse
|
|
53
|
+
server or hardware gain applied after this process is not observable by this probe.
|
|
54
|
+
Queue and Pulse ring requests are bounded; independent OS recordings, not level
|
|
55
|
+
events or packet counters, must establish sound quality and mute/interrupt latency.
|
|
56
|
+
Dynamic LATENCY messages recalculate the live graph's latency. Muting keeps the
|
|
57
|
+
receive graph running: flushing the renderer can propagate FLUSHING upstream and
|
|
58
|
+
stop WebRTC reception. Silent PCM drains the bounded speaker storage instead.
|
|
59
|
+
|
|
60
|
+
Official contracts:
|
|
61
|
+
|
|
62
|
+
- https://gstreamer.freedesktop.org/documentation/webrtc/
|
|
63
|
+
- https://gstreamer.freedesktop.org/documentation/webrtcdsp/webrtcdsp.html
|
|
64
|
+
- https://gstreamer.freedesktop.org/documentation/webrtcdsp/webrtcechoprobe.html
|
|
65
|
+
|
|
66
|
+
The component has been exercised on Arch userspace with GStreamer 1.28.8 and
|
|
67
|
+
PipeWire 1.6.9 using digital Pulse input/output devices. Tests cover independent
|
|
68
|
+
speaker recordings, mute/resume, command interruption, stale-output rejection,
|
|
69
|
+
default-device selection, level-cache expiry and stop/EOF/parent-death cleanup.
|
|
70
|
+
|
|
71
|
+
The host integration was also verified in the actual v0.25.0 Tauri window on
|
|
72
|
+
Arch/Hyprland with WebKitGTK 2.54.1 and DSH core 0.2.1-rc.4, a real signed-in account, digital audio devices
|
|
73
|
+
and synthetic spoken requests. It covered permission denial, capture/playback,
|
|
74
|
+
automatic speech-driven interruption, a fresh spoken answer, microphone/speaker
|
|
75
|
+
controls and hangup. No manual interrupt command was used in that call. Physical
|
|
76
|
+
microphone/speaker quality and acoustic echo cancellation/double-talk remain
|
|
77
|
+
unverified; digital-device evidence does not establish those properties.
|
|
78
|
+
|
|
79
|
+
Ubuntu 24.04's stock GStreamer 1.24.2 package omits webrtcdsp/webrtcechoprobe;
|
|
80
|
+
the capability probe correctly refuses to start there. A compatible media runtime
|
|
81
|
+
must be supplied before enabling this component on such a distribution. No runtime
|
|
82
|
+
installer is included. The component is not a replacement WebKit build.
|
|
83
|
+
|
|
84
|
+
The [earlier component baseline](https://github.com/WSL043/dsh-codex-subscription/actions/runs/40388255071)
|
|
85
|
+
completed two consecutive fresh call sequences in one media runtime, each with
|
|
86
|
+
17 passing checks and eight PCM positive/negative controls. The current
|
|
87
|
+
path-filtered workflow runs 19 checks per sequence, adding default-device and
|
|
88
|
+
level-cache regressions, and records each run's command-to-monitor-silence timing.
|
|
89
|
+
It runs on main and pull requests using the tested image digest and pinned Arch
|
|
90
|
+
package snapshot. These timings are not acoustic latency.
|
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Native voice media sidecar. No browser, credentials or arbitrary pipelines.
|
|
3
|
+
|
|
4
|
+
Requires Python GI: Gst, GstSdp, GstWebRTC 1.0, libnice and the fixed factories
|
|
5
|
+
listed in REQUIRED. JSON-lines protocol on stdin/stdout; diagnostics on stderr.
|
|
6
|
+
The DSH host owns confirmation, account signaling and the lifetime of each call.
|
|
7
|
+
"""
|
|
8
|
+
import ctypes
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import os
|
|
12
|
+
import queue
|
|
13
|
+
import re
|
|
14
|
+
import signal
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
MAX_LINE = 128 * 1024
|
|
20
|
+
REQUIRED = ('webrtcbin', 'pulsesrc', 'pulsesink', 'webrtcdsp', 'webrtcechoprobe',
|
|
21
|
+
'audioconvert', 'audioresample', 'capsfilter', 'queue', 'volume',
|
|
22
|
+
'level', 'opusenc', 'rtpopuspay', 'rtpopusdepay', 'opusdec')
|
|
23
|
+
RAW = 'audio/x-raw,format=S16LE,layout=interleaved,rate=48000,channels=1'
|
|
24
|
+
OUTPUT_LOCK = threading.Lock()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def emit(**message):
|
|
28
|
+
data = json.dumps(message, separators=(',', ':'), ensure_ascii=True)
|
|
29
|
+
if len(data.encode()) > MAX_LINE:
|
|
30
|
+
data = '{"event":"error","message":"protocol output too large"}'
|
|
31
|
+
with OUTPUT_LOCK:
|
|
32
|
+
try:
|
|
33
|
+
sys.stdout.write(data + '\n')
|
|
34
|
+
sys.stdout.flush()
|
|
35
|
+
except (BrokenPipeError, OSError):
|
|
36
|
+
os._exit(1)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
import gi
|
|
41
|
+
gi.require_version('Gst', '1.0')
|
|
42
|
+
gi.require_version('GstSdp', '1.0')
|
|
43
|
+
gi.require_version('GstWebRTC', '1.0')
|
|
44
|
+
from gi.repository import GLib, Gst, GstSdp, GstWebRTC
|
|
45
|
+
except (ImportError, ValueError):
|
|
46
|
+
emit(event='error', message='Python GI/Gst/GstSdp/GstWebRTC are required')
|
|
47
|
+
sys.exit(1)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Helper:
|
|
51
|
+
def __init__(self):
|
|
52
|
+
Gst.init(None)
|
|
53
|
+
self.loop = GLib.MainLoop()
|
|
54
|
+
self.commands = queue.Queue(maxsize=32)
|
|
55
|
+
self.parent = os.getppid()
|
|
56
|
+
self.pipeline = self.webrtc = self.channel = None
|
|
57
|
+
self.channels = []
|
|
58
|
+
self.role = 'offerer'
|
|
59
|
+
self.muted = self.output_muted = self.interrupted = False
|
|
60
|
+
self.remote_pad = None
|
|
61
|
+
self.pending_description = None
|
|
62
|
+
self.description_created = False
|
|
63
|
+
self.answer_set = False
|
|
64
|
+
self.generation = 0
|
|
65
|
+
self.input_cutoff = self.output_cutoff = 0
|
|
66
|
+
self.metrics_lock = threading.Lock()
|
|
67
|
+
self.metrics = {}
|
|
68
|
+
self.levels = {'mic': 0.0, 'assistant': 0.0}
|
|
69
|
+
self.level_seen = {'mic': 0.0, 'assistant': 0.0}
|
|
70
|
+
self.shutdown_requested = False
|
|
71
|
+
self.started_at = None
|
|
72
|
+
|
|
73
|
+
def reset_metrics(self):
|
|
74
|
+
self.levels = {'mic': 0.0, 'assistant': 0.0}
|
|
75
|
+
self.level_seen = {'mic': 0.0, 'assistant': 0.0}
|
|
76
|
+
self.metrics = dict(captureBuffers=0, captureSamples=0, rtpSent=0,
|
|
77
|
+
rtpReceived=0, decodedBuffers=0, playbackBuffers=0,
|
|
78
|
+
rtpBlockedByMute=0, rtpSentWhileMuted=0,
|
|
79
|
+
staleInputDropped=0, staleOutputDropped=0,
|
|
80
|
+
interrupts=0, dataMessagesReceived=0)
|
|
81
|
+
|
|
82
|
+
def snapshot(self):
|
|
83
|
+
with self.metrics_lock:
|
|
84
|
+
values = dict(self.metrics)
|
|
85
|
+
return dict(**values, active=self.pipeline is not None, pid=os.getpid(),
|
|
86
|
+
uptimeMs=round((time.monotonic() - self.started_at) * 1000) if self.started_at else 0,
|
|
87
|
+
muted=self.muted, outputMuted=self.output_muted,
|
|
88
|
+
interrupted=self.interrupted, generation=self.generation)
|
|
89
|
+
|
|
90
|
+
def increment(self, name, count=1):
|
|
91
|
+
with self.metrics_lock:
|
|
92
|
+
self.metrics[name] = self.metrics.get(name, 0) + count
|
|
93
|
+
|
|
94
|
+
def factory(self, factory, name, **properties):
|
|
95
|
+
element = Gst.ElementFactory.make(factory, name)
|
|
96
|
+
if element is None:
|
|
97
|
+
raise RuntimeError('required GStreamer element unavailable: ' + factory)
|
|
98
|
+
for key, value in properties.items():
|
|
99
|
+
element.set_property(key.replace('_', '-'), value)
|
|
100
|
+
self.pipeline.add(element)
|
|
101
|
+
return element
|
|
102
|
+
|
|
103
|
+
def fixed_queue(self, name):
|
|
104
|
+
return self.factory('queue', name, max_size_buffers=5, max_size_bytes=0,
|
|
105
|
+
max_size_time=100 * Gst.MSECOND, leaky=2)
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def link(*elements):
|
|
109
|
+
for first, second in zip(elements, elements[1:]):
|
|
110
|
+
if not first.link(second):
|
|
111
|
+
raise RuntimeError('fixed audio element link failed')
|
|
112
|
+
|
|
113
|
+
@staticmethod
|
|
114
|
+
def device(value):
|
|
115
|
+
if value is None:
|
|
116
|
+
return None
|
|
117
|
+
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9_.:@+-]{1,256}', value):
|
|
118
|
+
raise ValueError('device must be a PulseAudio device name')
|
|
119
|
+
return value
|
|
120
|
+
|
|
121
|
+
def running_time(self):
|
|
122
|
+
if self.pipeline is None or self.pipeline.get_clock() is None:
|
|
123
|
+
return 0
|
|
124
|
+
return max(0, self.pipeline.get_clock().get_time() - self.pipeline.get_base_time())
|
|
125
|
+
|
|
126
|
+
def start(self, command):
|
|
127
|
+
if command.get('captureAllowed') is not True:
|
|
128
|
+
raise ValueError('explicit captureAllowed:true is required')
|
|
129
|
+
if self.pipeline is not None:
|
|
130
|
+
raise ValueError('session already active')
|
|
131
|
+
self.role = command.get('role', 'offerer')
|
|
132
|
+
if self.role not in ('offerer', 'answerer'):
|
|
133
|
+
raise ValueError('role must be offerer or answerer')
|
|
134
|
+
input_device, output_device = self.device(command.get('inputDevice')), self.device(command.get('outputDevice'))
|
|
135
|
+
missing = [name for name in REQUIRED if Gst.ElementFactory.find(name) is None]
|
|
136
|
+
if missing:
|
|
137
|
+
raise RuntimeError('missing factories: ' + ','.join(missing))
|
|
138
|
+
self.reset_metrics()
|
|
139
|
+
self.started_at = time.monotonic()
|
|
140
|
+
self.generation += 1
|
|
141
|
+
epoch = self.generation
|
|
142
|
+
self.description_created = self.answer_set = False
|
|
143
|
+
self.pending_description = self.remote_pad = None
|
|
144
|
+
self.muted = self.output_muted = self.interrupted = False
|
|
145
|
+
self.input_cutoff = self.output_cutoff = 0
|
|
146
|
+
self.pipeline = Gst.Pipeline.new('native-voice')
|
|
147
|
+
# Official DSP contract: create probe before activating DSP sink, same pipeline.
|
|
148
|
+
self.echo = self.factory('webrtcechoprobe', 'voice_echo_probe')
|
|
149
|
+
self.webrtc = self.factory('webrtcbin', 'rtc', bundle_policy=GstWebRTC.WebRTCBundlePolicy.MAX_BUNDLE)
|
|
150
|
+
self.webrtc.set_property('latency', 60)
|
|
151
|
+
self.webrtc.connect('on-negotiation-needed', lambda _: GLib.idle_add(self.negotiate, epoch))
|
|
152
|
+
self.webrtc.connect('notify::ice-gathering-state', lambda *_: GLib.idle_add(self.gathered, epoch))
|
|
153
|
+
self.webrtc.connect('notify::connection-state', lambda *_: GLib.idle_add(self.connection_state, epoch))
|
|
154
|
+
self.webrtc.connect('pad-added', self.pad_added, epoch)
|
|
155
|
+
self.webrtc.connect('on-data-channel', lambda _, channel: self.attach_channel(channel, epoch))
|
|
156
|
+
# Keep the call separate from unrelated Python audio applications.
|
|
157
|
+
audio_identity = Gst.Structure.new_empty('props')
|
|
158
|
+
audio_identity.set_value('application.name', 'DSH Voice')
|
|
159
|
+
audio_identity.set_value('application.id', 'com.dsh.codex-subscription.voice')
|
|
160
|
+
source = self.factory('pulsesrc', 'microphone', do_timestamp=True,
|
|
161
|
+
buffer_time=100000, latency_time=10000,
|
|
162
|
+
client_name='DSH Voice', stream_properties=audio_identity,
|
|
163
|
+
device=input_device or '@DEFAULT_SOURCE@')
|
|
164
|
+
# NULL may restore an old per-application route instead of the selected
|
|
165
|
+
# system microphone. The Pulse default alias resolves that choice now.
|
|
166
|
+
convert = self.factory('audioconvert', 'mic_convert')
|
|
167
|
+
resample = self.factory('audioresample', 'mic_resample')
|
|
168
|
+
caps = self.factory('capsfilter', 'mic_caps', caps=Gst.Caps.from_string(RAW))
|
|
169
|
+
dsp = self.factory('webrtcdsp', 'mic_dsp', probe='voice_echo_probe', echo_cancel=True,
|
|
170
|
+
noise_suppression=True, gain_control=True)
|
|
171
|
+
mic_level = self.factory('level', 'mic_level', interval=30 * Gst.MSECOND, post_messages=True)
|
|
172
|
+
self.mic_volume = self.factory('volume', 'mic_mute', mute=False)
|
|
173
|
+
encoder = self.factory('opusenc', 'encoder', bitrate=24000, frame_size=20, inband_fec=True)
|
|
174
|
+
pay = self.factory('rtpopuspay', 'pay', pt=111)
|
|
175
|
+
rtp_caps = self.factory('capsfilter', 'rtp_caps', caps=Gst.Caps.from_string(
|
|
176
|
+
'application/x-rtp,media=audio,encoding-name=OPUS,clock-rate=48000,payload=111'))
|
|
177
|
+
self.link(source, convert, resample, caps, dsp, mic_level, self.mic_volume, encoder, pay, rtp_caps)
|
|
178
|
+
caps.get_static_pad('src').add_probe(Gst.PadProbeType.BUFFER, self.capture_probe, epoch)
|
|
179
|
+
rtp_caps.get_static_pad('src').add_probe(Gst.PadProbeType.BUFFER, self.send_probe, epoch)
|
|
180
|
+
request = self.webrtc.request_pad_simple('sink_%u')
|
|
181
|
+
if request is None or rtp_caps.get_static_pad('src').link(request) != Gst.PadLinkReturn.OK:
|
|
182
|
+
raise RuntimeError('WebRTC audio sender link failed')
|
|
183
|
+
self.rtc_sink = request
|
|
184
|
+
# Playback branch is fixed, native, and already contains the AEC reference.
|
|
185
|
+
self.rx_queue = self.fixed_queue('receive_queue')
|
|
186
|
+
depay = self.factory('rtpopusdepay', 'depay')
|
|
187
|
+
decoder = self.factory('opusdec', 'decoder', plc=True)
|
|
188
|
+
out_convert = self.factory('audioconvert', 'out_convert')
|
|
189
|
+
out_resample = self.factory('audioresample', 'out_resample')
|
|
190
|
+
out_caps = self.factory('capsfilter', 'out_caps', caps=Gst.Caps.from_string(RAW))
|
|
191
|
+
remote_level = self.factory('level', 'assistant_level', interval=30 * Gst.MSECOND, post_messages=True)
|
|
192
|
+
self.speaker_volume = self.factory('volume', 'speaker_mute', mute=False)
|
|
193
|
+
self.sink = self.factory('pulsesink', 'speaker', sync=True,
|
|
194
|
+
buffer_time=100000, latency_time=10000,
|
|
195
|
+
client_name='DSH Voice', stream_properties=audio_identity,
|
|
196
|
+
device=output_device or '@DEFAULT_SINK@')
|
|
197
|
+
self.sink.set_property('async', False)
|
|
198
|
+
self.link(self.rx_queue, depay, decoder, out_convert, out_resample, out_caps,
|
|
199
|
+
remote_level, self.speaker_volume, self.echo, self.sink)
|
|
200
|
+
remote_level.get_static_pad('src').add_probe(Gst.PadProbeType.BUFFER, self.decoded_probe, epoch)
|
|
201
|
+
self.speaker_volume.get_static_pad('sink').add_probe(Gst.PadProbeType.BUFFER, self.output_probe, epoch)
|
|
202
|
+
self.echo.get_static_pad('src').add_probe(Gst.PadProbeType.BUFFER, self.playback_probe, epoch)
|
|
203
|
+
bus = self.pipeline.get_bus()
|
|
204
|
+
bus.add_signal_watch()
|
|
205
|
+
bus.connect('message', self.bus_message, epoch)
|
|
206
|
+
self.bus = bus
|
|
207
|
+
if self.pipeline.set_state(Gst.State.READY) == Gst.StateChangeReturn.FAILURE:
|
|
208
|
+
raise RuntimeError('native pipeline READY failed')
|
|
209
|
+
self.channel = self.webrtc.emit('create-data-channel', 'oai-events', None)
|
|
210
|
+
if self.channel is None:
|
|
211
|
+
raise RuntimeError('data channel creation failed')
|
|
212
|
+
self.attach_channel(self.channel, epoch)
|
|
213
|
+
if self.pipeline.set_state(Gst.State.PLAYING) == Gst.StateChangeReturn.FAILURE:
|
|
214
|
+
raise RuntimeError('native pipeline PLAYING failed')
|
|
215
|
+
emit(event='state', state='connecting', pid=os.getpid(), generation=epoch)
|
|
216
|
+
|
|
217
|
+
def capture_probe(self, _pad, info, epoch):
|
|
218
|
+
if epoch != self.generation:
|
|
219
|
+
return Gst.PadProbeReturn.DROP
|
|
220
|
+
self.increment('captureBuffers')
|
|
221
|
+
self.increment('captureSamples', info.get_buffer().get_size() // 2)
|
|
222
|
+
return Gst.PadProbeReturn.OK
|
|
223
|
+
|
|
224
|
+
def send_probe(self, _pad, info, epoch):
|
|
225
|
+
buffer = info.get_buffer()
|
|
226
|
+
if epoch != self.generation:
|
|
227
|
+
return Gst.PadProbeReturn.DROP
|
|
228
|
+
if buffer.pts != Gst.CLOCK_TIME_NONE and buffer.pts < self.input_cutoff:
|
|
229
|
+
self.increment('staleInputDropped')
|
|
230
|
+
if self.muted:
|
|
231
|
+
self.increment('rtpBlockedByMute')
|
|
232
|
+
return Gst.PadProbeReturn.DROP
|
|
233
|
+
# mic_volume has already zeroed muted PCM before Opus encoding. Keep its
|
|
234
|
+
# silent RTP flowing: dropping numbered packets creates a jitter/PLC gap
|
|
235
|
+
# for the whole mute interval and delays the receiver when capture resumes.
|
|
236
|
+
if self.muted:
|
|
237
|
+
self.increment('rtpSentWhileMuted')
|
|
238
|
+
self.increment('rtpSent')
|
|
239
|
+
return Gst.PadProbeReturn.OK
|
|
240
|
+
|
|
241
|
+
def decoded_probe(self, _pad, _info, epoch):
|
|
242
|
+
if epoch == self.generation:
|
|
243
|
+
self.increment('decodedBuffers')
|
|
244
|
+
return Gst.PadProbeReturn.OK
|
|
245
|
+
|
|
246
|
+
def output_probe(self, _pad, info, epoch):
|
|
247
|
+
buffer = info.get_buffer()
|
|
248
|
+
if epoch != self.generation or (buffer.pts != Gst.CLOCK_TIME_NONE and buffer.pts < self.output_cutoff):
|
|
249
|
+
self.increment('staleOutputDropped')
|
|
250
|
+
return Gst.PadProbeReturn.DROP
|
|
251
|
+
return Gst.PadProbeReturn.OK
|
|
252
|
+
|
|
253
|
+
def playback_probe(self, _pad, _info, epoch):
|
|
254
|
+
if epoch == self.generation:
|
|
255
|
+
self.increment('playbackBuffers')
|
|
256
|
+
return Gst.PadProbeReturn.OK
|
|
257
|
+
|
|
258
|
+
def pad_added(self, _rtc, pad, epoch):
|
|
259
|
+
if pad.get_direction() != Gst.PadDirection.SRC or epoch != self.generation:
|
|
260
|
+
return
|
|
261
|
+
caps = pad.get_current_caps() or pad.query_caps(None)
|
|
262
|
+
if caps is None or caps.is_empty() or caps.get_structure(0).get_string('media') != 'audio':
|
|
263
|
+
return
|
|
264
|
+
if self.remote_pad is not None:
|
|
265
|
+
GLib.idle_add(self.fail, 'unexpected second incoming audio track')
|
|
266
|
+
return
|
|
267
|
+
self.remote_pad = pad
|
|
268
|
+
pad.add_probe(Gst.PadProbeType.BUFFER, self.receive_probe, epoch)
|
|
269
|
+
if pad.link(self.rx_queue.get_static_pad('sink')) != Gst.PadLinkReturn.OK:
|
|
270
|
+
GLib.idle_add(self.fail, 'incoming RTP link failed')
|
|
271
|
+
|
|
272
|
+
def receive_probe(self, _pad, _info, epoch):
|
|
273
|
+
if epoch == self.generation:
|
|
274
|
+
self.increment('rtpReceived')
|
|
275
|
+
return Gst.PadProbeReturn.OK
|
|
276
|
+
|
|
277
|
+
def data_message(self, size):
|
|
278
|
+
self.increment('dataMessagesReceived')
|
|
279
|
+
emit(event='data', bytes=size) # Never echo user text or credentials.
|
|
280
|
+
|
|
281
|
+
def attach_channel(self, channel, epoch):
|
|
282
|
+
self.channels.append(channel)
|
|
283
|
+
channel.connect('on-open', lambda *_: emit(event='state', state='data-channel-open')
|
|
284
|
+
if epoch == self.generation and self.pipeline is not None else None)
|
|
285
|
+
channel.connect('on-message-string', lambda _, text: self.data_message(len(text.encode()))
|
|
286
|
+
if epoch == self.generation and self.pipeline is not None else None)
|
|
287
|
+
|
|
288
|
+
def promise(self, callback, epoch):
|
|
289
|
+
def changed(promise, *_):
|
|
290
|
+
GLib.idle_add(callback, promise, epoch)
|
|
291
|
+
return Gst.Promise.new_with_change_func(changed, None, None)
|
|
292
|
+
|
|
293
|
+
def negotiate(self, epoch):
|
|
294
|
+
if self.pipeline is None or epoch != self.generation or self.role != 'offerer' or self.description_created:
|
|
295
|
+
return False
|
|
296
|
+
self.description_created = True
|
|
297
|
+
self.webrtc.emit('create-offer', None, self.promise(lambda p, e: self.local_created(p, e, 'offer'), epoch))
|
|
298
|
+
return False
|
|
299
|
+
|
|
300
|
+
def local_created(self, promise, epoch, kind):
|
|
301
|
+
if epoch != self.generation or self.pipeline is None:
|
|
302
|
+
return False
|
|
303
|
+
reply = promise.get_reply()
|
|
304
|
+
if reply is None or not reply.has_field(kind):
|
|
305
|
+
return self.fail('local description creation failed')
|
|
306
|
+
description = reply.get_value(kind)
|
|
307
|
+
self.pending_description = kind
|
|
308
|
+
self.webrtc.emit('set-local-description', description, self.promise(self.local_applied, epoch))
|
|
309
|
+
return False
|
|
310
|
+
|
|
311
|
+
def local_applied(self, promise, epoch):
|
|
312
|
+
reply = promise.get_reply()
|
|
313
|
+
if reply is not None and reply.has_field('error'):
|
|
314
|
+
return self.fail('local description apply failed')
|
|
315
|
+
return self.gathered(epoch)
|
|
316
|
+
|
|
317
|
+
def gathered(self, epoch):
|
|
318
|
+
if epoch != self.generation or self.pipeline is None or self.pending_description is None:
|
|
319
|
+
return False
|
|
320
|
+
if self.webrtc.get_property('ice-gathering-state') != GstWebRTC.WebRTCICEGatheringState.COMPLETE:
|
|
321
|
+
return False
|
|
322
|
+
description = self.webrtc.get_property('local-description')
|
|
323
|
+
if description is not None:
|
|
324
|
+
kind, self.pending_description = self.pending_description, None
|
|
325
|
+
emit(event=kind, sdp=description.sdp.as_text())
|
|
326
|
+
return False
|
|
327
|
+
|
|
328
|
+
def remote(self, command):
|
|
329
|
+
if self.pipeline is None:
|
|
330
|
+
raise ValueError('session not active')
|
|
331
|
+
kind = command.get('descriptionType', command.get('type'))
|
|
332
|
+
sdp = command.get('sdp')
|
|
333
|
+
if kind not in ('offer', 'answer') or not isinstance(sdp, str) or not 0 < len(sdp.encode()) < 100 * 1024:
|
|
334
|
+
raise ValueError('valid bounded offer/answer SDP is required')
|
|
335
|
+
if (kind == 'offer') != (self.role == 'answerer') or self.answer_set:
|
|
336
|
+
raise ValueError('unexpected remote description for role or session')
|
|
337
|
+
result, message = GstSdp.SDPMessage.new()
|
|
338
|
+
if result != GstSdp.SDPResult.OK or GstSdp.sdp_message_parse_buffer(sdp.encode(), message) != GstSdp.SDPResult.OK:
|
|
339
|
+
raise ValueError('SDP could not be parsed')
|
|
340
|
+
description = GstWebRTC.WebRTCSessionDescription.new(
|
|
341
|
+
GstWebRTC.WebRTCSDPType.OFFER if kind == 'offer' else GstWebRTC.WebRTCSDPType.ANSWER, message)
|
|
342
|
+
self.answer_set = True
|
|
343
|
+
self.webrtc.emit('set-remote-description', description, self.promise(
|
|
344
|
+
lambda promise, epoch: self.remote_applied(promise, epoch, kind), self.generation))
|
|
345
|
+
|
|
346
|
+
def remote_applied(self, promise, epoch, kind):
|
|
347
|
+
if epoch != self.generation or self.pipeline is None:
|
|
348
|
+
return False
|
|
349
|
+
reply = promise.get_reply()
|
|
350
|
+
if reply is not None and reply.has_field('error'):
|
|
351
|
+
return self.fail('remote description apply failed')
|
|
352
|
+
if kind == 'offer':
|
|
353
|
+
self.webrtc.emit('create-answer', None, self.promise(lambda p, e: self.local_created(p, e, 'answer'), epoch))
|
|
354
|
+
return False
|
|
355
|
+
|
|
356
|
+
def connection_state(self, epoch):
|
|
357
|
+
if self.pipeline is not None and epoch == self.generation:
|
|
358
|
+
state = self.webrtc.get_property('connection-state').value_nick
|
|
359
|
+
emit(event='state', state=state)
|
|
360
|
+
if state in ('failed', 'closed'):
|
|
361
|
+
self.fail('WebRTC connection ' + state)
|
|
362
|
+
return False
|
|
363
|
+
|
|
364
|
+
def bus_message(self, _bus, message, epoch):
|
|
365
|
+
if epoch != self.generation or self.pipeline is None:
|
|
366
|
+
return
|
|
367
|
+
if message.type == Gst.MessageType.ERROR:
|
|
368
|
+
error, _debug = message.parse_error()
|
|
369
|
+
print('GStreamer error from ' + message.src.get_name() + ': ' + error.message, file=sys.stderr, flush=True)
|
|
370
|
+
self.fail('native GStreamer pipeline error')
|
|
371
|
+
elif message.type == Gst.MessageType.LATENCY:
|
|
372
|
+
# Incoming WebRTC pads change the live graph after PLAYING.
|
|
373
|
+
self.pipeline.recalculate_latency()
|
|
374
|
+
elif message.type == Gst.MessageType.EOS:
|
|
375
|
+
self.fail('unexpected native audio end-of-stream')
|
|
376
|
+
elif message.type == Gst.MessageType.ELEMENT:
|
|
377
|
+
structure = message.get_structure()
|
|
378
|
+
if structure is not None and structure.get_name() == 'level':
|
|
379
|
+
rms = structure.get_value('rms')
|
|
380
|
+
level = max((10 ** (float(value) / 20) for value in rms if math.isfinite(float(value))), default=0)
|
|
381
|
+
key = 'mic' if message.src.get_name() == 'mic_level' else 'assistant'
|
|
382
|
+
now = time.monotonic()
|
|
383
|
+
self.level_seen[key] = now
|
|
384
|
+
self.levels[key] = min(1.0, level)
|
|
385
|
+
# A live service may stop sending RTP during an interruption.
|
|
386
|
+
# Silence then has no level message of its own; never retain a
|
|
387
|
+
# positive speaker level forever and prevent the gate resuming.
|
|
388
|
+
for channel in self.levels:
|
|
389
|
+
if now - self.level_seen[channel] > .25:
|
|
390
|
+
self.levels[channel] = 0.0
|
|
391
|
+
emit(event='level', **self.levels)
|
|
392
|
+
|
|
393
|
+
def controls(self, command):
|
|
394
|
+
if self.pipeline is None:
|
|
395
|
+
raise ValueError('session not active')
|
|
396
|
+
kind = command['type']
|
|
397
|
+
if kind in ('mute', 'outputMute') and not isinstance(command.get('muted'), bool):
|
|
398
|
+
raise ValueError('muted must be boolean')
|
|
399
|
+
if kind == 'mute':
|
|
400
|
+
self.muted = command['muted']
|
|
401
|
+
self.mic_volume.set_property('mute', self.muted)
|
|
402
|
+
self.input_cutoff = self.running_time()
|
|
403
|
+
elif kind == 'outputMute':
|
|
404
|
+
self.output_muted = command['muted']
|
|
405
|
+
elif kind == 'interrupt':
|
|
406
|
+
self.interrupted = True
|
|
407
|
+
self.increment('interrupts')
|
|
408
|
+
elif kind == 'resume':
|
|
409
|
+
self.output_cutoff = self.running_time()
|
|
410
|
+
self.interrupted = False
|
|
411
|
+
self.speaker_volume.set_property('mute', self.output_muted or self.interrupted)
|
|
412
|
+
# Drain the bounded renderer as silent PCM. A downstream flush can return
|
|
413
|
+
# FLUSHING upstream and permanently stop WebRTC reception.
|
|
414
|
+
return dict(monotonicNs=time.monotonic_ns(), metrics=self.snapshot())
|
|
415
|
+
|
|
416
|
+
def stop(self):
|
|
417
|
+
pipeline, self.pipeline = self.pipeline, None
|
|
418
|
+
if pipeline is not None:
|
|
419
|
+
self.generation += 1
|
|
420
|
+
self.channel = None
|
|
421
|
+
self.channels = []
|
|
422
|
+
pipeline.set_state(Gst.State.NULL)
|
|
423
|
+
result, state, _pending = pipeline.get_state(5 * Gst.SECOND)
|
|
424
|
+
if state != Gst.State.NULL:
|
|
425
|
+
raise RuntimeError('native audio did not stop within deadline')
|
|
426
|
+
self.bus.remove_signal_watch()
|
|
427
|
+
self.webrtc = self.remote_pad = None
|
|
428
|
+
emit(event='closed', metrics=self.snapshot(), monotonicNs=time.monotonic_ns())
|
|
429
|
+
|
|
430
|
+
def fail(self, message):
|
|
431
|
+
emit(event='error', message=message)
|
|
432
|
+
try:
|
|
433
|
+
self.stop()
|
|
434
|
+
except Exception:
|
|
435
|
+
emit(event='error', message='native cleanup failed')
|
|
436
|
+
return False
|
|
437
|
+
|
|
438
|
+
def command(self, command):
|
|
439
|
+
identifier = command.get('id')
|
|
440
|
+
kind = command.get('type')
|
|
441
|
+
try:
|
|
442
|
+
if kind == 'probe':
|
|
443
|
+
missing = [name for name in REQUIRED if Gst.ElementFactory.find(name) is None]
|
|
444
|
+
value = dict(available=not missing, missing=missing, gstreamer=Gst.version_string(), metrics=self.snapshot())
|
|
445
|
+
elif kind == 'start':
|
|
446
|
+
self.start(command)
|
|
447
|
+
value = dict(pid=os.getpid(), metrics=self.snapshot())
|
|
448
|
+
elif kind in ('remote', 'offer', 'answer'):
|
|
449
|
+
self.remote(command)
|
|
450
|
+
value = {}
|
|
451
|
+
elif kind in ('mute', 'outputMute', 'interrupt', 'resume'):
|
|
452
|
+
value = self.controls(command)
|
|
453
|
+
elif kind == 'send':
|
|
454
|
+
data = command.get('data')
|
|
455
|
+
if not isinstance(data, str) or len(data.encode()) > 16 * 1024 or self.channel is None:
|
|
456
|
+
raise ValueError('bounded data and active channel required')
|
|
457
|
+
self.channel.emit('send-string', data)
|
|
458
|
+
value = {}
|
|
459
|
+
elif kind == 'stop':
|
|
460
|
+
self.stop()
|
|
461
|
+
value = dict(metrics=self.snapshot())
|
|
462
|
+
else:
|
|
463
|
+
raise ValueError('unknown command')
|
|
464
|
+
emit(id=identifier, ok=True, **value)
|
|
465
|
+
except (ValueError, RuntimeError) as error:
|
|
466
|
+
emit(id=identifier, ok=False, message=str(error))
|
|
467
|
+
if kind in ('start', 'remote', 'offer', 'answer'):
|
|
468
|
+
self.fail('session setup failed')
|
|
469
|
+
except Exception as error:
|
|
470
|
+
print('native helper operation failed: ' + type(error).__name__, file=sys.stderr, flush=True)
|
|
471
|
+
emit(id=identifier, ok=False, message='native helper operation failed')
|
|
472
|
+
self.fail('native helper operation failed')
|
|
473
|
+
|
|
474
|
+
def read_commands(self):
|
|
475
|
+
try:
|
|
476
|
+
while True:
|
|
477
|
+
raw = sys.stdin.buffer.readline(MAX_LINE + 1)
|
|
478
|
+
if not raw:
|
|
479
|
+
GLib.idle_add(self.shutdown)
|
|
480
|
+
return
|
|
481
|
+
if len(raw) > MAX_LINE:
|
|
482
|
+
raise ValueError('protocol input too large')
|
|
483
|
+
message = json.loads(raw)
|
|
484
|
+
if not isinstance(message, dict) or not isinstance(message.get('id'), (int, str)):
|
|
485
|
+
raise ValueError('command object with id required')
|
|
486
|
+
self.commands.put_nowait(message)
|
|
487
|
+
except (ValueError, UnicodeError, OSError, queue.Full):
|
|
488
|
+
emit(event='error', message='invalid or overflowing command stream')
|
|
489
|
+
GLib.idle_add(self.shutdown)
|
|
490
|
+
|
|
491
|
+
def pump(self):
|
|
492
|
+
for _ in range(8):
|
|
493
|
+
try:
|
|
494
|
+
command = self.commands.get_nowait()
|
|
495
|
+
except queue.Empty:
|
|
496
|
+
break
|
|
497
|
+
self.command(command)
|
|
498
|
+
if os.getppid() != self.parent:
|
|
499
|
+
return self.shutdown()
|
|
500
|
+
return not self.shutdown_requested
|
|
501
|
+
|
|
502
|
+
def shutdown(self):
|
|
503
|
+
self.shutdown_requested = True
|
|
504
|
+
try:
|
|
505
|
+
self.stop()
|
|
506
|
+
finally:
|
|
507
|
+
self.loop.quit()
|
|
508
|
+
return False
|
|
509
|
+
|
|
510
|
+
def run(self):
|
|
511
|
+
# Linux parent-death notification plus PID polling closes orphan sessions.
|
|
512
|
+
if sys.platform.startswith('linux'):
|
|
513
|
+
try:
|
|
514
|
+
ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)
|
|
515
|
+
except (AttributeError, OSError):
|
|
516
|
+
pass
|
|
517
|
+
for number in (signal.SIGINT, signal.SIGTERM):
|
|
518
|
+
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, number, self.shutdown)
|
|
519
|
+
threading.Thread(target=self.read_commands, daemon=True).start()
|
|
520
|
+
GLib.timeout_add(10, self.pump)
|
|
521
|
+
try:
|
|
522
|
+
self.loop.run()
|
|
523
|
+
finally:
|
|
524
|
+
self.shutdown()
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
if __name__ == '__main__':
|
|
528
|
+
Helper().run()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-codex-subscription",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.9",
|
|
4
4
|
"description": "Use ChatGPT and Codex subscriptions in DeepSeek Harness with OAuth, quota, safe resets, web search, images and Fast mode, and control DSH from the ChatGPT mobile app (Beta)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
},
|
|
14
14
|
"files": [
|
|
15
15
|
"lib/*.js",
|
|
16
|
+
"native/linux-voice-helper.py",
|
|
16
17
|
"locale/*.json",
|
|
17
18
|
"cordis.patch.yml",
|
|
18
19
|
"README.md",
|