Debian Codegraph @

Xpjproject/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2016 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19 #include "MyApp.h"
20 #include <memory>
21 #include <winerror.h>
22 #include <pplawait.h>
23
24 using namespace VoipBackEnd;
25 using namespace Windows::Storage;
26
27 const std::string CONFIG_NAME = "pjsua2.json";
28 const int SIP_PORT = 5060;
29 const int LOG_LEVEL = 5;
30 const std::string THIS_FILE = "MyApp.cpp";
31
32 #define GenHresultFromITF(x) (MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, x))
33
34 MyAppRT^ MyAppRT::singleton = nullptr;
35
36 #define DEFAULT_DESTRUCTOR() \
37 delete inPtr;
38
39 #define CHECK_EXCEPTION(expr) \
40 do { \
41 try { \
42 (expr); \
43 } catch (pj::Error e) { \
44 Platform::Exception^ exp = ref new Platform::COMException( \
45 GenHresultFromITF(e.status)); \
46 } \
47 } while (0)
48
49 ///////////////////////////////////////////////////////////////////////////////
50 std::string make_string(const std::wstring& wstring)
51 {
52 auto wideData = wstring.c_str();
53 int bufferSize = WideCharToMultiByte(CP_UTF8, 0, wideData,
54 -1, nullptr, 0, NULL, NULL);
55
56 std::unique_ptr<char[]> utf8;
57 utf8.reset(new char[bufferSize]);
58
59 if (WideCharToMultiByte(CP_UTF8, 0, wideData, -1,
60 utf8.get(), bufferSize, NULL, NULL) == 0)
61 {
62 return std::string();
63 }
64
65 return std::string(utf8.get());
66 }
67
68 std::wstring make_wstring(const std::string& string)
69 {
70 auto utf8Data = string.c_str();
71 int bufferSize = MultiByteToWideChar(CP_UTF8, 0, utf8Data, -1, nullptr, 0);
72
73 std::unique_ptr<wchar_t[]> wide;
74 wide.reset(new wchar_t[bufferSize]);
75
76 if (MultiByteToWideChar(CP_UTF8, 0, utf8Data, -1,
77 wide.get(), bufferSize) == 0)
78 {
79 return std::wstring();
80 }
81
82 return std::wstring(wide.get());;
83 }
84
85 std::string to_std_str(Platform::String ^in_str)
86 {
87 std::wstring wsstr(in_str->Data());
88 return make_string(wsstr);
89 }
90
91 Platform::String^ to_platform_str(const std::string& in_str)
92 {
93 std::wstring wsstr = make_wstring(in_str);
94 return ref new Platform::String(wsstr.c_str(), wsstr.length());
95 }
96
97 ///////////////////////////////////////////////////////////////////////////////
98 void ImpLogWriter::write(const pj::LogEntry &entry)
99 {
100 std::wstring msg = make_wstring(entry.msg) + L"\r\n";
101
102 ::OutputDebugString(msg.c_str());
103 }
104 ///////////////////////////////////////////////////////////////////////////////
105 OnRegStateParamRT::OnRegStateParamRT(const pj::OnRegStateParam& param)
106
107 {
108 inPtr = new pj::OnRegStateParam(param);
109 }
110
111 OnRegStateParamRT::OnRegStateParamRT()
112 {
113 inPtr = new pj::OnRegStateParam();
114 }
115
116 OnRegStateParamRT::~OnRegStateParamRT()
117 {
118 DEFAULT_DESTRUCTOR();
119 }
120
121 pj_status_t OnRegStateParamRT::status::get()
122 {
123 return inPtr->status;
124 }
125
126 unsigned OnRegStateParamRT::code::get()
127 {
128 return static_cast<unsigned>(inPtr->code);
129 }
130
131 Platform::String^ OnRegStateParamRT::reason::get()
132 {
133 return to_platform_str(inPtr->reason);
134 }
135
136 int OnRegStateParamRT::expiration::get()
137 {
138 return inPtr->expiration;
139 }
140 ///////////////////////////////////////////////////////////////////////////////
141 void ImpAccount::setCallback(IntAccount^ callback)
142 {
143 cb = callback;
144 }
145
146 void ImpAccount::onIncomingCall(pj::OnIncomingCallParam& prm)
147 {
148 if (cb) {
149 if (MyAppRT::Instance->handleIncomingCall(prm.callId)) {
150 CallInfoRT^ info = MyAppRT::Instance->getCallInfo();
151 if (info != nullptr)
152 cb->onIncomingCall(info);
153 }
154 }
155 }
156
157
158 void ImpAccount::onRegState(pj::OnRegStateParam& prm)
159 {
160 if (cb)
161 cb->onRegState(ref new OnRegStateParamRT(prm));
162 }
163
164 ///////////////////////////////////////////////////////////////////////////////
165 CallInfoRT::CallInfoRT(const pj::CallInfo& info)
166 {
167 inPtr = new pj::CallInfo(info);
168 }
169
170 Platform::String^ CallInfoRT::localUri::get()
171 {
172 return to_platform_str(inPtr->localUri);
173 }
174
175 Platform::String^ CallInfoRT::localContact::get()
176 {
177 return to_platform_str(inPtr->localContact);
178 }
179
180 Platform::String^ CallInfoRT::remoteUri::get()
181 {
182 return to_platform_str(inPtr->remoteUri);
183 }
184
185 Platform::String^ CallInfoRT::remoteContact::get()
186 {
187 return to_platform_str(inPtr->remoteContact);
188 }
189
190 INV_STATE CallInfoRT::state::get()
191 {
192 return static_cast<INV_STATE>(inPtr->state);
193 }
194
195 CallInfoRT::~CallInfoRT()
196 {
197 DEFAULT_DESTRUCTOR();
198 }
199 ///////////////////////////////////////////////////////////////////////////////
200 CallOpParamRT::CallOpParamRT()
201 {
202 inPtr = new pj::CallOpParam(true);
203 }
204
205 unsigned CallOpParamRT::statusCode::get()
206 {
207 return static_cast<unsigned>(inPtr->statusCode);
208 }
209
210 void CallOpParamRT::statusCode::set(unsigned val)
211 {
212 inPtr->statusCode = static_cast<pjsip_status_code>(val);
213 }
214
215 Platform::String^ CallOpParamRT::reason::get()
216 {
217 return to_platform_str(inPtr->reason);
218 }
219
220 void CallOpParamRT::reason::set(Platform::String^ val)
221 {
222 inPtr->reason = to_std_str(val);
223 }
224
225 pj::CallOpParam* CallOpParamRT::getPtr()
226 {
227 return inPtr;
228 }
229
230 CallOpParamRT::~CallOpParamRT()
231 {
232 DEFAULT_DESTRUCTOR();
233 }
234
235 ///////////////////////////////////////////////////////////////////////////////
236 ImpCall::ImpCall(pj::Account& account, int call_id) : pj::Call(account,call_id)
237 {};
238
239 void ImpCall::setCallback(IntCall^ callback)
240 {
241 cb = callback;
242 }
243
244 void ImpCall::onCallState(pj::OnCallStateParam& prm)
245 {
246 if (cb) {
247 pj::CallInfo info = getInfo();
248 cb->onCallState(ref new CallInfoRT(info));
249 }
250 };
251
252 void ImpCall::onCallMediaState(pj::OnCallMediaStateParam& prm)
253 {
254 pj::CallInfo info;
255 try {
256 info = getInfo();
257 } catch (pj::Error& e) {
258 MyAppRT::Instance->writeLog(2, to_platform_str(e.info()));
259 return;
260 }
261
262 for (unsigned i = 0; i < info.media.size(); i++) {
263 pj::CallMediaInfo med_info = info.media[i];
264 if ((med_info.type == PJMEDIA_TYPE_AUDIO) &&
265 ((med_info.status == PJSUA_CALL_MEDIA_ACTIVE) ||
266 (med_info.status == PJSUA_CALL_MEDIA_REMOTE_HOLD))
267 )
268 {
269 pj::Media* m = getMedia(i);
270 pj::AudioMedia *am = pj::AudioMedia::typecastFromMedia(m);
271 pj::AudDevManager& aud_mgr =
272 pj::Endpoint::instance().audDevManager();
273
274 try {
275 aud_mgr.getCaptureDevMedia().startTransmit(*am);
276 am->startTransmit(aud_mgr.getPlaybackDevMedia());
277
278 } catch (pj::Error& e) {
279 MyAppRT::Instance->writeLog(2, to_platform_str(e.info()));
280 continue;
281 }
282 }
283 }
284 };
285 ///////////////////////////////////////////////////////////////////////////////
286
287 AccountInfo::AccountInfo(pj::AccountConfig* accConfig) : cfg(accConfig)
288 {}
289
290 Platform::String^ AccountInfo::id::get() {
291 return to_platform_str(cfg->idUri);
292 }
293
294 Platform::String^ AccountInfo::registrar::get() {
295 return to_platform_str(cfg->regConfig.registrarUri);
296 }
297
298 Platform::String^ AccountInfo::proxy::get() {
299 if (!cfg->sipConfig.proxies.empty()) {
300 return to_platform_str(cfg->sipConfig.proxies[0]);
301 } else {
302 return ref new Platform::String(L"");
303 }
304 }
305
306 Platform::String^ AccountInfo::username::get() {
307 if (!cfg->sipConfig.authCreds.empty()) {
308 pj::AuthCredInfo& info = cfg->sipConfig.authCreds[0];
309
310 return to_platform_str(info.username);
311 } else {
312 return ref new Platform::String(L"");
313 }
314 }
315
316 Platform::String^ AccountInfo::password::get() {
317 if (!cfg->sipConfig.authCreds.empty()) {
318 pj::AuthCredInfo& info = cfg->sipConfig.authCreds[0];
319
320 return to_platform_str(info.data);
321 } else {
322 return ref new Platform::String(L"");
323 }
324 }
325
326 ///////////////////////////////////////////////////////////////////////////////
327 MyAppRT::MyAppRT()
328 {
329 logWriter = new ImpLogWriter();
330
331 StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
332
333 appDir = to_std_str(localFolder->Path);
334 }
335
336 MyAppRT::~MyAppRT()
337 {
338 delete logWriter;
339 if (account)
340 delete account;
341
342 if (epConfig)
343 delete epConfig;
344
345 if (accConfig)
346 delete accConfig;
347
348 if (sipTpConfig)
349 delete sipTpConfig;
350 }
351
352 void MyAppRT::loadConfig()
353 {
354 pj::JsonDocument* json = new pj::JsonDocument();
355
356 std::string configPath = appDir + "/" + CONFIG_NAME;
357
358 try {
359 /* Load file */
360 json->loadFile(configPath);
361 pj::ContainerNode root = json->getRootContainer();
362
363 /* Read endpoint config */
364 epConfig->readObject(root);
365
366 /* Read transport config */
367 pj::ContainerNode tp_node = root.readContainer("SipTransport");
368 sipTpConfig->readObject(tp_node);
369
370 /* Read account configs */
371 pj::ContainerNode acc_node = root.readContainer("Account");
372 accConfig->readObject(acc_node);
373 } catch (pj::Error) {
374 ep.utilLogWrite(2, "loadConfig", "Failed loading config");
375
376 sipTpConfig->port = SIP_PORT;
377 }
378
379 delete json;
380 }
381
382 void MyAppRT::saveConfig()
383 {
384 pj::JsonDocument* json = new pj::JsonDocument();
385
386 std::string configPath = appDir + "/" + CONFIG_NAME;
387
388 try {
389 /* Write endpoint config */
390 json->writeObject(*epConfig);
391
392 /* Write transport config */
393 pj::ContainerNode tp_node = json->writeNewContainer("SipTransport");
394 sipTpConfig->writeObject(tp_node);
395
396 /* Write account configs */
397 pj::ContainerNode acc_node = json->writeNewContainer("Account");
398 accConfig->writeObject(acc_node);
399
400 /* Save file */
401 json->saveFile(configPath);
402 } catch (pj::Error) {
403 ep.utilLogWrite(2, "saveConfig", "Failed saving config");
404
405 sipTpConfig->port = SIP_PORT;
406 }
407
408 delete json;
409 }
410
411 MyAppRT^ MyAppRT::Instance::get()
412 {
413 if (MyAppRT::singleton == nullptr)
414 {
415 if (MyAppRT::singleton == nullptr)
416 {
417 MyAppRT::singleton = ref new MyAppRT();
418 }
419 }
420
421 return MyAppRT::singleton;
422 }
423
424 void MyAppRT::init(IntAccount^ iAcc, IntCall^ iCall)
425 {
426 /* Create endpoint */
427 try {
428 ep.libCreate();
429 } catch (pj::Error e) {
430 return;
431 }
432
433 intAcc = iAcc;
434 intCall = iCall;
435
436 epConfig = new pj::EpConfig;
437 accConfig = new pj::AccountConfig;
438 sipTpConfig = new pj::TransportConfig;
439
440 /* Load config */
441 loadConfig();
442
443 /* Override log level setting */
444 epConfig->logConfig.level = LOG_LEVEL;
445 epConfig->logConfig.consoleLevel = LOG_LEVEL;
446
447 /* Set log config. */
448 pj::LogConfig *log_cfg = &epConfig->logConfig;
449 log_cfg->writer = logWriter;
450 log_cfg->decor = log_cfg->decor &
451 ~(::pj_log_decoration::PJ_LOG_HAS_CR |
452 ::pj_log_decoration::PJ_LOG_HAS_NEWLINE);
453
454 /* Set ua config. */
455 pj::UaConfig* ua_cfg = &epConfig->uaConfig;
456 ua_cfg->userAgent = "Pjsua2 WinRT " + ep.libVersion().full;
457 ua_cfg->mainThreadOnly = false;
458
459 /* Init endpoint */
460 try
461 {
462 ep.libInit(*epConfig);
463 } catch (pj::Error& e)
464 {
465 ep.utilLogWrite(2,THIS_FILE,e.info());
466 return;
467 }
468
469 /* Create transports. */
470
471 try {
472 sipTpConfig->port = 5060;
473 ep.transportCreate(::pjsip_transport_type_e::PJSIP_TRANSPORT_TCP,
474 *sipTpConfig);
475 } catch (pj::Error& e) {
476 ep.utilLogWrite(2,THIS_FILE,e.info());
477 }
478
479 try {
480 ep.transportCreate(::pjsip_transport_type_e::PJSIP_TRANSPORT_UDP,
481 *sipTpConfig);
482 } catch (pj::Error& e) {
483 ep.utilLogWrite(2,THIS_FILE,e.info());
484 }
485
486 /* Create accounts. */
487 account = new ImpAccount();
488 if (accConfig->idUri.length() == 0) {
489 accConfig->idUri = "sip:localhost";
490 } else {
491 ua_cfg->stunServer.push_back("stun.pjsip.org");
492 }
493 //accConfig->natConfig.iceEnabled = true;
494 account->create(*accConfig);
495 account->setCallback(iAcc);
496
497 /* Start. */
498 try {
499 ep.libStart();
500 } catch (pj::Error& e) {
501 ep.utilLogWrite(2,THIS_FILE,e.info());
502 return;
503 }
504 }
505
506 void MyAppRT::deInit()
507 {
508 saveConfig();
509
510 try {
511 ep.libDestroy();
512 } catch (pj::Error) {}
513
514 }
515
516 void MyAppRT::writeLog(int level, Platform::String^ message)
517 {
518 ep.utilLogWrite(level, "MyAppRT", to_std_str(message));
519 }
520
521 void MyAppRT::hangupCall()
522 {
523 if (activeCall) {
524 if (!isThreadRegistered())
525 {
526 registerThread("hangupCall");
527 }
528
529 delete activeCall;
530 activeCall = NULL;
531 }
532 };
533
534 void MyAppRT::answerCall(CallOpParamRT^ prm)
535 {
536 if (!isThreadRegistered())
537 {
538 registerThread("answerCall");
539 }
540 CHECK_EXCEPTION(activeCall->answer(*prm->getPtr()));
541 };
542
543 void MyAppRT::makeCall(Platform::String^ dst_uri)
544 {
545 if (!isThreadRegistered())
546 {
547 registerThread("makeCall");
548 }
549 CallOpParamRT^ param = ref new CallOpParamRT;
550 activeCall = new ImpCall(*account, -1);
551 activeCall->setCallback(intCall);
552
553 CHECK_EXCEPTION(activeCall->makeCall(to_std_str(dst_uri),*param->getPtr()));
554 };
555
556 CallInfoRT^ MyAppRT::getCallInfo()
557 {
558 if (activeCall) {
559 pj::CallInfo info = activeCall->getInfo();
560 return ref new CallInfoRT(info);
561 }
562
563 return nullptr;
564 }
565
566 pj_bool_t MyAppRT::handleIncomingCall(int callId)
567 {
568 if (activeCall) {
569 return PJ_FALSE;
570 }
571
572 activeCall = new ImpCall(*account, callId);
573 activeCall->setCallback(intCall);
574
575 return PJ_TRUE;
576 }
577
578 void MyAppRT::registerThread(Platform::String^ name)
579 {
580 CHECK_EXCEPTION(ep.libRegisterThread(to_std_str(name)));
581 }
582
583 bool MyAppRT::isThreadRegistered()
584 {
585 // Some threads are registered using PJLIB API, ep.libIsThreadRegistered() will return false on those threads.
586 //return ep.libIsThreadRegistered();
587 return pj_thread_is_registered() != PJ_FALSE;
588 }
589
590 AccountInfo^ MyAppRT::getAccountInfo()
591
592 {
593 return ref new AccountInfo(accConfig);
594 }
595
596 void MyAppRT::modifyAccount(Platform::String^ id,
597 Platform::String^ registrar,
598 Platform::String^ proxy,
599 Platform::String^ username,
600 Platform::String^ password)
601 {
602 if (id->IsEmpty()) {
603 accConfig->idUri = "sip:localhost";
604 accConfig->regConfig.registrarUri = "";
605 accConfig->sipConfig.authCreds.clear();
606 accConfig->sipConfig.proxies.clear();
607 } else {
608 pj::AuthCredInfo info = pj::AuthCredInfo("Digest", "*",
609 to_std_str(username), 0,
610 to_std_str(password));
611
612 accConfig->idUri = to_std_str(id);
613 accConfig->regConfig.registrarUri = to_std_str(registrar);
614
615 accConfig->sipConfig.authCreds.clear();
616 accConfig->sipConfig.authCreds.push_back(info);
617
618 accConfig->sipConfig.proxies.clear();
619 accConfig->sipConfig.proxies.push_back(to_std_str(proxy));
620 }
621
622 if (!isThreadRegistered())
623 {
624 registerThread("registerAccount");
625 }
626
627 account->modify(*accConfig);
628
629 /* Save config. */
630 saveConfig();
631 }