PjsuaCommunicator.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. #include "PjsuaCommunicator.hpp"
  2. #include <pjlib.h>
  3. #include <pjsua-lib/pjsua.h>
  4. #include <boost/algorithm/string.hpp>
  5. #include <boost/format.hpp>
  6. using namespace std;
  7. namespace sip {
  8. using namespace log4cpp;
  9. class _LogWriter : public pj::LogWriter {
  10. public:
  11. _LogWriter(Category &logger)
  12. : logger(logger) { }
  13. virtual void write(const pj::LogEntry &entry) override {
  14. auto message = entry.msg.substr(0, entry.msg.size() - 1); // remove newline
  15. logger << prioritiesMap.at(entry.level) << message;
  16. }
  17. private:
  18. log4cpp::Category &logger;
  19. std::map<int, Priority::Value> prioritiesMap = {
  20. {1, Priority::ERROR},
  21. {2, Priority::WARN},
  22. {3, Priority::NOTICE},
  23. {4, Priority::INFO},
  24. {5, Priority::DEBUG},
  25. {6, Priority::DEBUG}
  26. };
  27. };
  28. class _MumlibAudioMedia : public pj::AudioMedia {
  29. public:
  30. _MumlibAudioMedia(sip::PjsuaCommunicator &comm, int frameTimeLength)
  31. : communicator(comm) {
  32. createMediaPort(frameTimeLength);
  33. registerMediaPort(&mediaPort);
  34. }
  35. ~_MumlibAudioMedia() {
  36. unregisterMediaPort();
  37. }
  38. private:
  39. pjmedia_port mediaPort;
  40. sip::PjsuaCommunicator &communicator;
  41. static pj_status_t callback_getFrame(pjmedia_port *port, pjmedia_frame *frame) {
  42. auto *communicator = static_cast<sip::PjsuaCommunicator *>(port->port_data.pdata);
  43. return communicator->mediaPortGetFrame(port, frame);
  44. }
  45. static pj_status_t callback_putFrame(pjmedia_port *port, pjmedia_frame *frame) {
  46. auto *communicator = static_cast<sip::PjsuaCommunicator *>(port->port_data.pdata);
  47. return communicator->mediaPortPutFrame(port, frame);
  48. }
  49. void createMediaPort(int frameTimeLength) {
  50. auto name = pj_str((char *) "MumsiMediaPort");
  51. if (frameTimeLength != 10
  52. and frameTimeLength != 20
  53. and frameTimeLength != 40
  54. and frameTimeLength != 60) {
  55. throw sip::Exception(
  56. (boost::format("valid frame time length value: %d. valid values are: 10, 20, 40, 60") %
  57. frameTimeLength).str());
  58. }
  59. pj_status_t status = pjmedia_port_info_init(&(mediaPort.info),
  60. &name,
  61. PJMEDIA_SIG_CLASS_PORT_AUD('s', 'i'),
  62. SAMPLING_RATE,
  63. 1,
  64. 16,
  65. SAMPLING_RATE * frameTimeLength / 1000);
  66. if (status != PJ_SUCCESS) {
  67. throw sip::Exception("error while calling pjmedia_port_info_init()", status);
  68. }
  69. mediaPort.port_data.pdata = &communicator;
  70. mediaPort.get_frame = &callback_getFrame;
  71. mediaPort.put_frame = &callback_putFrame;
  72. }
  73. };
  74. class _Call : public pj::Call {
  75. public:
  76. _Call(sip::PjsuaCommunicator &comm, pj::Account &acc, int call_id = PJSUA_INVALID_ID)
  77. : pj::Call(acc, call_id),
  78. communicator(comm),
  79. account(acc) { }
  80. virtual void onCallState(pj::OnCallStateParam &prm) override;
  81. virtual void onCallMediaState(pj::OnCallMediaStateParam &prm) override;
  82. virtual void onDtmfDigit(pj::OnDtmfDigitParam &prm) override;
  83. private:
  84. sip::PjsuaCommunicator &communicator;
  85. pj::Account &account;
  86. };
  87. class _Account : public pj::Account {
  88. public:
  89. _Account(sip::PjsuaCommunicator &comm)
  90. : communicator(comm) { }
  91. virtual void onRegState(pj::OnRegStateParam &prm) override;
  92. virtual void onIncomingCall(pj::OnIncomingCallParam &iprm) override;
  93. private:
  94. sip::PjsuaCommunicator &communicator;
  95. bool available = true;
  96. friend class _Call;
  97. };
  98. void _Call::onCallState(pj::OnCallStateParam &prm) {
  99. auto ci = getInfo();
  100. communicator.logger.info("Call %d state=%s.", ci.id, ci.stateText.c_str());
  101. string address = ci.remoteUri;
  102. boost::replace_all(address, "<", "");
  103. boost::replace_all(address, ">", "");
  104. if (ci.state == PJSIP_INV_STATE_CONFIRMED) {
  105. auto msgText = "Incoming call from " + address + ".";
  106. communicator.logger.notice(msgText);
  107. communicator.onStateChange(msgText);
  108. communicator.onMuteDeafChange(0);
  109. } else if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
  110. auto &acc = dynamic_cast<_Account &>(account);
  111. if (not acc.available) {
  112. auto msgText = "Call from " + address + " finished.";
  113. communicator.mixer->clear();
  114. communicator.logger.notice(msgText);
  115. communicator.onStateChange(msgText);
  116. communicator.onMuteDeafChange(1);
  117. acc.available = true;
  118. }
  119. delete this;
  120. }
  121. }
  122. void _Call::onCallMediaState(pj::OnCallMediaStateParam &prm) {
  123. auto ci = getInfo();
  124. if (ci.media.size() != 1) {
  125. throw sip::Exception("ci.media.size is not 1");
  126. }
  127. if (ci.media[0].status == PJSUA_CALL_MEDIA_ACTIVE) {
  128. auto *aud_med = static_cast<pj::AudioMedia *>(getMedia(0));
  129. communicator.media->startTransmit(*aud_med);
  130. aud_med->startTransmit(*communicator.media);
  131. } else if (ci.media[0].status == PJSUA_CALL_MEDIA_NONE) {
  132. dynamic_cast<_Account &>(account).available = true;
  133. }
  134. }
  135. void _Call::onDtmfDigit(pj::OnDtmfDigitParam &prm) {
  136. communicator.logger.notice("DTMF digit '%s' (call %d).", prm.digit.c_str(), getId());
  137. }
  138. void _Account::onRegState(pj::OnRegStateParam &prm) {
  139. pj::AccountInfo ai = getInfo();
  140. communicator.logger << log4cpp::Priority::INFO
  141. << (ai.regIsActive ? "Register:" : "Unregister:") << " code=" << prm.code;
  142. }
  143. void _Account::onIncomingCall(pj::OnIncomingCallParam &iprm) {
  144. auto *call = new _Call(communicator, *this, iprm.callId);
  145. string uri = call->getInfo().remoteUri;
  146. communicator.logger.info("Incoming call from %s.", uri.c_str());
  147. pj::CallOpParam param;
  148. if (communicator.uriValidator.validateUri(uri)) {
  149. if (available) {
  150. param.statusCode = PJSIP_SC_OK;
  151. available = false;
  152. } else {
  153. param.statusCode = PJSIP_SC_BUSY_EVERYWHERE;
  154. }
  155. call->answer(param);
  156. } else {
  157. communicator.logger.warn("Refusing call from %s.", uri.c_str());
  158. param.statusCode = PJSIP_SC_SERVICE_UNAVAILABLE;
  159. call->hangup(param);
  160. }
  161. }
  162. }
  163. sip::PjsuaCommunicator::PjsuaCommunicator(IncomingConnectionValidator &validator, int frameTimeLength)
  164. : logger(log4cpp::Category::getInstance("SipCommunicator")),
  165. pjsuaLogger(log4cpp::Category::getInstance("Pjsua")),
  166. uriValidator(validator) {
  167. logWriter.reset(new sip::_LogWriter(pjsuaLogger));
  168. endpoint.libCreate();
  169. pj::EpConfig endpointConfig;
  170. endpointConfig.uaConfig.userAgent = "Mumsi Mumble-SIP gateway";
  171. endpointConfig.uaConfig.maxCalls = 1;
  172. endpointConfig.logConfig.writer = logWriter.get();
  173. endpointConfig.logConfig.level = 5;
  174. endpointConfig.medConfig.noVad = true;
  175. endpoint.libInit(endpointConfig);
  176. pj_caching_pool_init(&cachingPool, &pj_pool_factory_default_policy, 0);
  177. mixer.reset(new mixer::AudioFramesMixer(cachingPool.factory));
  178. media.reset(new _MumlibAudioMedia(*this, frameTimeLength));
  179. logger.info("Created Pjsua communicator with frame length %d ms.", frameTimeLength);
  180. }
  181. void sip::PjsuaCommunicator::connect(
  182. std::string host,
  183. std::string user,
  184. std::string password,
  185. unsigned int port) {
  186. pj::TransportConfig transportConfig;
  187. transportConfig.port = port;
  188. endpoint.transportCreate(PJSIP_TRANSPORT_UDP, transportConfig); // todo try catch
  189. endpoint.libStart();
  190. pj_status_t status = pjsua_set_null_snd_dev();
  191. if (status != PJ_SUCCESS) {
  192. throw sip::Exception("error in pjsua_set_null_std_dev()", status);
  193. }
  194. registerAccount(host, user, password);
  195. }
  196. sip::PjsuaCommunicator::~PjsuaCommunicator() {
  197. endpoint.libDestroy();
  198. }
  199. void sip::PjsuaCommunicator::sendPcmSamples(int sessionId, int sequenceNumber, int16_t *samples, unsigned int length) {
  200. mixer->addFrameToBuffer(sessionId, sequenceNumber, samples, length);
  201. }
  202. pj_status_t sip::PjsuaCommunicator::mediaPortGetFrame(pjmedia_port *port, pjmedia_frame *frame) {
  203. frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
  204. pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
  205. pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&(port->info));
  206. const int readSamples = mixer->getMixedSamples(samples, count);
  207. if (readSamples < count) {
  208. pjsuaLogger.debug("Requested %d samples, available %d, filling remaining with zeros.",
  209. count, readSamples);
  210. for (int i = readSamples; i < count; ++i) {
  211. samples[i] = 0;
  212. }
  213. }
  214. return PJ_SUCCESS;
  215. }
  216. pj_status_t sip::PjsuaCommunicator::mediaPortPutFrame(pjmedia_port *port, pjmedia_frame *frame) {
  217. pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
  218. pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&port->info);
  219. frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
  220. if (count > 0) {
  221. pjsuaLogger.debug("Calling onIncomingPcmSamples with %d samples.", count);
  222. onIncomingPcmSamples(samples, count);
  223. }
  224. return PJ_SUCCESS;
  225. }
  226. void sip::PjsuaCommunicator::registerAccount(string host, string user, string password) {
  227. string uri = "sip:" + user + "@" + host;
  228. pj::AccountConfig accountConfig;
  229. accountConfig.idUri = uri;
  230. accountConfig.regConfig.registrarUri = "sip:" + host;
  231. pj::AuthCredInfo cred("digest", "*", user, 0, password);
  232. accountConfig.sipConfig.authCreds.push_back(cred);
  233. logger.info("Registering account for URI: %s.", uri.c_str());
  234. account.reset(new _Account(*this));
  235. account->create(accountConfig);
  236. }