| 1 |
import pjsua2 as pj |
| 2 |
import sys |
| 3 |
import os |
| 4 |
import time |
| 5 |
from collections import deque |
| 6 |
import struct |
| 7 |
import gc |
| 8 |
from random import randint |
| 9 |
import threading |
| 10 |
|
| 11 |
write=sys.stdout.write |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
def ua_data_test(): |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
write("UA data types test..") |
| 22 |
the_realm = "pjsip.org" |
| 23 |
ci = pj.AuthCredInfo() |
| 24 |
ci.realm = the_realm |
| 25 |
ci.dataType = 20 |
| 26 |
|
| 27 |
ci2 = ci |
| 28 |
assert ci.dataType == 20 |
| 29 |
assert ci2.realm == the_realm |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
uc = pj.UaConfig() |
| 36 |
uc.maxCalls = 10 |
| 37 |
uc.userAgent = "Python" |
| 38 |
uc.nameserver = pj.StringVector(["10.0.0.1", "10.0.0.2"]) |
| 39 |
uc.nameserver.append("NS1") |
| 40 |
|
| 41 |
uc2 = uc |
| 42 |
assert uc2.maxCalls == 10 |
| 43 |
assert uc2.userAgent == "Python" |
| 44 |
assert len(uc2.nameserver) == 3 |
| 45 |
assert uc2.nameserver[0] == "10.0.0.1" |
| 46 |
assert uc2.nameserver[1] == "10.0.0.2" |
| 47 |
assert uc2.nameserver[2] == "NS1" |
| 48 |
|
| 49 |
write(" Dumping nameservers: " + "\r\n") |
| 50 |
for s in uc2.nameserver: |
| 51 |
write(s + "\r\n") |
| 52 |
write("\r\n") |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
bv = pj.ByteVector() |
| 60 |
bv.assign_from_bytes(bytearray([1, 2, 3])) |
| 61 |
assert bv.size() == 3 |
| 62 |
assert bv[0] == 1 and bv[1] == 2 and bv[2] == 3 |
| 63 |
|
| 64 |
ba = memoryview(bytearray(5)) |
| 65 |
bv.copy_to_bytearray(ba[1:]) |
| 66 |
assert ba == b'\x00\x01\x02\x03\x00' |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
def ua_run_test_exception(): |
| 72 |
write("Exception test.." + "\r\n") |
| 73 |
ep = pj.Endpoint() |
| 74 |
ep.libCreate() |
| 75 |
got_exception = False |
| 76 |
try: |
| 77 |
ep.natDetectType() |
| 78 |
except pj.Error as e: |
| 79 |
|
| 80 |
got_exception = True |
| 81 |
write(" Got exception: status=%u, reason=%s,\n title=%s,\n srcFile=%s, srcLine=%d" % \ |
| 82 |
(e.status, e.reason, e.title, e.srcFile, e.srcLine) + "\r\n") |
| 83 |
assert e.status == 370050 |
| 84 |
assert e.reason.find("PJNATH_ESTUNINSERVER") >= 0 |
| 85 |
assert e.title == "pjsua_detect_nat_type()" |
| 86 |
assert got_exception |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
class MyLogWriter(pj.LogWriter): |
| 92 |
def write(self, entry): |
| 93 |
write("This is Python:" + entry.msg + "\r\n") |
| 94 |
|
| 95 |
class AMP(pj.AudioMediaPort): |
| 96 |
buffers = deque() |
| 97 |
|
| 98 |
def onFrameRequested(self, frame): |
| 99 |
if len(self.buffers): |
| 100 |
|
| 101 |
buffer_out = self.buffers.popleft() |
| 102 |
|
| 103 |
frame.type = pj.PJMEDIA_TYPE_AUDIO |
| 104 |
frame.buf.assign_from_bytes(buffer_out) |
| 105 |
|
| 106 |
def onFrameReceived(self, frame): |
| 107 |
|
| 108 |
buffer_in = bytearray(frame.buf.size()) |
| 109 |
frame.buf.copy_to_bytearray(buffer_in) |
| 110 |
|
| 111 |
buffer_out = bytearray(len(buffer_in)) |
| 112 |
|
| 113 |
|
| 114 |
for i in range(len(buffer_in)): |
| 115 |
if (i % 2 == 1): |
| 116 |
|
| 117 |
x = buffer_in[i] << 8 | buffer_in[i-1] |
| 118 |
x = struct.unpack('<h', struct.pack('<H', x))[0] |
| 119 |
|
| 120 |
|
| 121 |
x = int(x * 1.5) |
| 122 |
if x > 32767: |
| 123 |
x = 32767 |
| 124 |
elif x < -32768: |
| 125 |
x = -32768 |
| 126 |
|
| 127 |
|
| 128 |
x = struct.unpack('<H', struct.pack('<h', x))[0] |
| 129 |
|
| 130 |
|
| 131 |
buffer_out[i-1] = (x & 0xff) |
| 132 |
buffer_out[i] = (x & 0xff00) >> 8 |
| 133 |
|
| 134 |
self.buffers.append(buffer_out) |
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
def ua_run_log_test(): |
| 140 |
write("Logging test.." + "\r\n") |
| 141 |
ep_cfg = pj.EpConfig() |
| 142 |
|
| 143 |
lw = MyLogWriter() |
| 144 |
ep_cfg.logConfig.writer = lw |
| 145 |
ep_cfg.logConfig.decor = ep_cfg.logConfig.decor & ~(pj.PJ_LOG_HAS_CR | pj.PJ_LOG_HAS_NEWLINE) |
| 146 |
|
| 147 |
ep = pj.Endpoint() |
| 148 |
ep.libCreate() |
| 149 |
ep.libInit(ep_cfg) |
| 150 |
ep.libDestroy() |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
def ua_run_ua_test(): |
| 156 |
write("UA test run.." + "\r\n") |
| 157 |
ep_cfg = pj.EpConfig() |
| 158 |
|
| 159 |
ep = pj.Endpoint() |
| 160 |
ep.libCreate() |
| 161 |
ep.libInit(ep_cfg) |
| 162 |
ep.libStart() |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
amp = AMP() |
| 167 |
fmt = pj.MediaFormatAudio() |
| 168 |
fmt.type = pj.PJMEDIA_TYPE_AUDIO |
| 169 |
fmt.clockRate = 16000 |
| 170 |
fmt.channelCount = 1 |
| 171 |
fmt.bitsPerSample = 16 |
| 172 |
fmt.frameTimeUsec = 20000 |
| 173 |
amp.createPort("amp", fmt) |
| 174 |
ep.audDevManager().getCaptureDevMedia().startTransmit(amp) |
| 175 |
amp.startTransmit(ep.audDevManager().getPlaybackDevMedia()) |
| 176 |
|
| 177 |
time.sleep(3) |
| 178 |
del amp |
| 179 |
write("************* Endpoint started ok, now shutting down... *************" + "\r\n") |
| 180 |
ep.libDestroy() |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
def ua_tonegen_test(): |
| 186 |
write("UA tonegen test.." + "\r\n") |
| 187 |
ep_cfg = pj.EpConfig() |
| 188 |
|
| 189 |
ep = pj.Endpoint() |
| 190 |
ep.libCreate() |
| 191 |
ep.libInit(ep_cfg) |
| 192 |
ep.libStart() |
| 193 |
|
| 194 |
tonegen = pj.ToneGenerator() |
| 195 |
tonegen.createToneGenerator() |
| 196 |
|
| 197 |
tone = pj.ToneDesc() |
| 198 |
tone.freq1 = 400 |
| 199 |
tone.freq2 = 600 |
| 200 |
tone.on_msec = 1000 |
| 201 |
tone.off_msec = 1000 |
| 202 |
tones = pj.ToneDescVector() |
| 203 |
tones.append(tone) |
| 204 |
|
| 205 |
digit = pj.ToneDigit() |
| 206 |
digit.digit = '0' |
| 207 |
digit.on_msec = 1000 |
| 208 |
digit.off_msec = 1000 |
| 209 |
digits = pj.ToneDigitVector() |
| 210 |
digits.append(digit) |
| 211 |
|
| 212 |
adm = ep.audDevManager() |
| 213 |
spk = adm.getPlaybackDevMedia() |
| 214 |
|
| 215 |
tonegen.play(tones, True) |
| 216 |
tonegen.startTransmit(spk) |
| 217 |
time.sleep(5) |
| 218 |
|
| 219 |
tonegen.stop() |
| 220 |
tonegen.playDigits(digits, True) |
| 221 |
time.sleep(5) |
| 222 |
|
| 223 |
dm = tonegen.getDigitMap() |
| 224 |
write(dm[0].digit + "\r\n") |
| 225 |
dm[0].freq1 = 400 |
| 226 |
dm[0].freq2 = 600 |
| 227 |
tonegen.setDigitMap(dm) |
| 228 |
|
| 229 |
tonegen.stop() |
| 230 |
tonegen.playDigits(digits, True) |
| 231 |
time.sleep(5) |
| 232 |
|
| 233 |
tonegen = None |
| 234 |
|
| 235 |
ep.libDestroy() |
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
class MyAiPort(pj.AudioMediaAiPort): |
| 241 |
"""Custom AI port that collects events.""" |
| 242 |
def __init__(self): |
| 243 |
super().__init__() |
| 244 |
self.events = [] |
| 245 |
self.connected = False |
| 246 |
self.transcripts = [] |
| 247 |
|
| 248 |
def onEvent(self, event): |
| 249 |
self.events.append(event.type) |
| 250 |
if event.type == pj.PJMEDIA_AI_EVENT_CONNECTED: |
| 251 |
self.connected = True |
| 252 |
write(" [AI] Connected\r\n") |
| 253 |
elif event.type == pj.PJMEDIA_AI_EVENT_DISCONNECTED: |
| 254 |
self.connected = False |
| 255 |
write(" [AI] Disconnected\r\n") |
| 256 |
elif event.type == pj.PJMEDIA_AI_EVENT_TRANSCRIPT: |
| 257 |
self.transcripts.append(event.text) |
| 258 |
write(" [AI] " + event.text + "\r\n") |
| 259 |
elif event.type == pj.PJMEDIA_AI_EVENT_RESPONSE_DONE: |
| 260 |
write(" [AI] Response done\r\n") |
| 261 |
|
| 262 |
def ua_ai_port_test(): |
| 263 |
write("AI media port test.." + "\r\n") |
| 264 |
ep_cfg = pj.EpConfig() |
| 265 |
|
| 266 |
ep = pj.Endpoint() |
| 267 |
ep.libCreate() |
| 268 |
ep.libInit(ep_cfg) |
| 269 |
ep.libStart() |
| 270 |
|
| 271 |
|
| 272 |
ai = MyAiPort() |
| 273 |
prm = pj.AiMediaPortParam() |
| 274 |
assert prm.vadEnabled == False |
| 275 |
assert prm.ptimeMsec == 20 |
| 276 |
|
| 277 |
ai.createPort(prm) |
| 278 |
write(" AI port created and registered to conf bridge\r\n") |
| 279 |
|
| 280 |
|
| 281 |
ai.startTransmit(ep.audDevManager().getPlaybackDevMedia()) |
| 282 |
ep.audDevManager().getCaptureDevMedia().startTransmit(ai) |
| 283 |
write(" Audio routing established\r\n") |
| 284 |
|
| 285 |
|
| 286 |
api_key = os.environ.get("OPENAI_API_KEY", "") |
| 287 |
if api_key: |
| 288 |
url = ("wss://api.openai.com/v1/realtime" |
| 289 |
"?model=gpt-4o-mini-realtime-preview") |
| 290 |
write(" Connecting to OpenAI..\r\n") |
| 291 |
ai.connect(url, api_key) |
| 292 |
|
| 293 |
|
| 294 |
for i in range(150): |
| 295 |
ep.libHandleEvents(100) |
| 296 |
if ai.connected: |
| 297 |
break |
| 298 |
|
| 299 |
if ai.connected: |
| 300 |
write(" Connected! Speak into your mic.\r\n") |
| 301 |
write(" Press ENTER to stop.\r\n") |
| 302 |
input() |
| 303 |
|
| 304 |
write(" Disconnecting..\r\n") |
| 305 |
ai.disconnect() |
| 306 |
|
| 307 |
for i in range(20): |
| 308 |
ep.libHandleEvents(100) |
| 309 |
else: |
| 310 |
write(" Connection timeout (non-fatal)\r\n") |
| 311 |
else: |
| 312 |
write(" OPENAI_API_KEY not set, skipping AI connection test\r\n") |
| 313 |
|
| 314 |
|
| 315 |
ai.stopTransmit(ep.audDevManager().getPlaybackDevMedia()) |
| 316 |
ep.audDevManager().getCaptureDevMedia().stopTransmit(ai) |
| 317 |
write(" Audio routing disconnected\r\n") |
| 318 |
|
| 319 |
del ai |
| 320 |
write(" AI port destroyed\r\n") |
| 321 |
|
| 322 |
ep.libDestroy() |
| 323 |
write(" AI media port test OK\r\n") |
| 324 |
|
| 325 |
|
| 326 |
class RandomIntVal(): |
| 327 |
def __init__(self): |
| 328 |
self.value = randint(0, 100000) |
| 329 |
|
| 330 |
class TestJob(pj.PendingJob): |
| 331 |
def __init__(self): |
| 332 |
super().__init__() |
| 333 |
self.val = RandomIntVal() |
| 334 |
print("Job created id:", id(self), "value:", self.val.value) |
| 335 |
|
| 336 |
def execute(self, is_pending): |
| 337 |
print("Executing job value:", self.val.value, is_pending) |
| 338 |
|
| 339 |
def __del__(self): |
| 340 |
print("Job deleted id:", id(self), "value:", self.val.value) |
| 341 |
|
| 342 |
def add_new_job1(ep): |
| 343 |
print("Creating job 1") |
| 344 |
job = TestJob() |
| 345 |
print("Adding job 1") |
| 346 |
ep.utilAddPendingJob(job) |
| 347 |
|
| 348 |
|
| 349 |
def add_new_job2(ep): |
| 350 |
ep.libRegisterThread("thread") |
| 351 |
print("Creating job 2") |
| 352 |
job = TestJob() |
| 353 |
print("Adding job 2") |
| 354 |
ep.utilAddPendingJob(job) |
| 355 |
|
| 356 |
def ua_pending_job_test(): |
| 357 |
write("PendingJob test.." + "\r\n") |
| 358 |
ep_cfg = pj.EpConfig() |
| 359 |
ep_cfg.uaConfig.threadCnt = 0 |
| 360 |
ep_cfg.uaConfig.mainThreadOnly = True |
| 361 |
|
| 362 |
ep = pj.Endpoint() |
| 363 |
ep.libCreate() |
| 364 |
ep.libInit(ep_cfg) |
| 365 |
ep.libStart() |
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
add_new_job1(ep) |
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
my_thread = threading.Thread(target=add_new_job2, args=(ep,)) |
| 374 |
my_thread.start() |
| 375 |
|
| 376 |
time.sleep(1) |
| 377 |
print("Collecting gc 1") |
| 378 |
gc.collect() |
| 379 |
|
| 380 |
print("Handling events") |
| 381 |
for _ in range(100): |
| 382 |
ep.libHandleEvents(10) |
| 383 |
|
| 384 |
print("Collecting gc 2") |
| 385 |
gc.collect() |
| 386 |
|
| 387 |
ep.libDestroy() |
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
if __name__ == "__main__": |
| 393 |
ua_data_test() |
| 394 |
ua_run_test_exception() |
| 395 |
ua_run_log_test() |
| 396 |
ua_run_ua_test() |
| 397 |
ua_ai_port_test() |
| 398 |
ua_tonegen_test() |
| 399 |
ua_pending_job_test() |
| 400 |
sys.exit(0) |
| 401 |
|
| 402 |
|