PjsuaCommunicator.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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) {
  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)
  31. : communicator(comm) {
  32. createMediaPort();
  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() {
  50. auto name = pj_str((char *) "MumsiMediaPort");
  51. pj_status_t status = pjmedia_port_info_init(&(mediaPort.info),
  52. &name,
  53. PJMEDIA_SIG_CLASS_PORT_AUD('s', 'i'),
  54. SAMPLING_RATE,
  55. 1,
  56. 16,
  57. SAMPLING_RATE * 20 /
  58. 1000); // todo recalculate to match mumble specs
  59. if (status != PJ_SUCCESS) {
  60. throw sip::Exception("error while calling pjmedia_port_info_init()", status);
  61. }
  62. mediaPort.port_data.pdata = &communicator;
  63. mediaPort.get_frame = &callback_getFrame;
  64. mediaPort.put_frame = &callback_putFrame;
  65. }
  66. };
  67. class _Call : public pj::Call {
  68. public:
  69. _Call(sip::PjsuaCommunicator &comm, pj::Account &acc, int call_id = PJSUA_INVALID_ID)
  70. : pj::Call(acc, call_id),
  71. communicator(comm),
  72. account(acc) { }
  73. virtual void onCallState(pj::OnCallStateParam &prm) {
  74. auto ci = getInfo();
  75. communicator.logger.info("Call %d state=%s.", ci.id, ci.stateText.c_str());
  76. string address = ci.remoteUri;
  77. boost::replace_all(address, "<", "");
  78. boost::replace_all(address, ">", "");
  79. if (ci.state == PJSIP_INV_STATE_CONFIRMED) {
  80. auto msgText = "Incoming call from " + address + ".";
  81. communicator.logger.notice(msgText);
  82. communicator.onStateChange(msgText);
  83. } else if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
  84. auto msgText = "Call from " + address + " finished.";
  85. communicator.logger.notice(msgText);
  86. communicator.onStateChange(msgText);
  87. delete this;
  88. }
  89. }
  90. virtual void onCallMediaState(pj::OnCallMediaStateParam &prm) {
  91. auto ci = getInfo();
  92. if (ci.media.size() != 1) {
  93. throw sip::Exception("ci.media.size is not 1");
  94. }
  95. if (ci.media[0].status == PJSUA_CALL_MEDIA_ACTIVE) {
  96. auto *aud_med = static_cast<pj::AudioMedia *>(getMedia(0));
  97. communicator.media->startTransmit(*aud_med);
  98. aud_med->startTransmit(*communicator.media);
  99. }
  100. }
  101. virtual void onDtmfDigit(pj::OnDtmfDigitParam &prm) {
  102. communicator.logger.notice("DTMF digit '%s' (call %d).", prm.digit.c_str(), getId());
  103. }
  104. private:
  105. sip::PjsuaCommunicator &communicator;
  106. pj::Account &account;
  107. };
  108. class _Account : public pj::Account {
  109. public:
  110. _Account(sip::PjsuaCommunicator &comm)
  111. : communicator(comm) { }
  112. virtual void onRegState(pj::OnRegStateParam &prm) {
  113. pj::AccountInfo ai = getInfo();
  114. communicator.logger << log4cpp::Priority::INFO
  115. << (ai.regIsActive ? "Register:" : "Unregister:") << " code=" << prm.code;
  116. }
  117. virtual void onIncomingCall(pj::OnIncomingCallParam &iprm) {
  118. auto *call = new _Call(communicator, *this, iprm.callId);
  119. communicator.logger.info("Incoming call from %s.", call->getInfo().remoteUri.c_str());
  120. pj::CallOpParam param;
  121. param.statusCode = PJSIP_SC_OK;
  122. call->answer(param);
  123. }
  124. private:
  125. sip::PjsuaCommunicator &communicator;
  126. friend class _Call;
  127. };
  128. }
  129. sip::PjsuaCommunicator::PjsuaCommunicator()
  130. : logger(log4cpp::Category::getInstance("SipCommunicator")),
  131. pjsuaLogger(log4cpp::Category::getInstance("Pjsua")) {
  132. logWriter.reset(new sip::_LogWriter(pjsuaLogger));
  133. endpoint.libCreate();
  134. pj::EpConfig endpointConfig;
  135. endpointConfig.uaConfig.userAgent = "Mumsi Mumble-SIP gateway";
  136. endpointConfig.uaConfig.maxCalls = 1;
  137. endpointConfig.logConfig.writer = logWriter.get();
  138. endpointConfig.logConfig.level = 5;
  139. endpointConfig.medConfig.noVad = true;
  140. endpoint.libInit(endpointConfig);
  141. pj_status_t status;
  142. pj_caching_pool cachingPool;
  143. pj_caching_pool_init(&cachingPool, &pj_pool_factory_default_policy, 0);
  144. pool = pj_pool_create(&cachingPool.factory, "media", 32768, 8192, nullptr);
  145. if (!pool) {
  146. throw sip::Exception("error when creating memory pool", status);
  147. }
  148. // todo calculate sizes
  149. status = pjmedia_circ_buf_create(pool, 960 * 10, &inputBuff);
  150. if (status != PJ_SUCCESS) {
  151. throw sip::Exception("error when creating circular buffer", status);
  152. }
  153. media.reset(new _MumlibAudioMedia(*this));
  154. }
  155. void sip::PjsuaCommunicator::connect(
  156. std::string host,
  157. std::string user,
  158. std::string password,
  159. unsigned int port) {
  160. pj::TransportConfig transportConfig;
  161. transportConfig.port = port;
  162. endpoint.transportCreate(PJSIP_TRANSPORT_UDP, transportConfig); // todo try catch
  163. endpoint.libStart();
  164. pj_status_t status = pjsua_set_null_snd_dev();
  165. if (status != PJ_SUCCESS) {
  166. throw sip::Exception("error in pjsua_set_null_std_dev()", status);
  167. }
  168. registerAccount(host, user, password);
  169. }
  170. sip::PjsuaCommunicator::~PjsuaCommunicator() {
  171. endpoint.libDestroy();
  172. }
  173. pj_status_t sip::PjsuaCommunicator::mediaPortGetFrame(pjmedia_port *port, pjmedia_frame *frame) {
  174. std::unique_lock<std::mutex> lock(inBuffAccessMutex);
  175. frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
  176. pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
  177. pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&(port->info));
  178. pj_size_t availableSamples = pjmedia_circ_buf_get_len(inputBuff);
  179. const int samplesToRead = std::min(count, availableSamples);
  180. pjsuaLogger.debug("Pulling %d samples from in-buff.", samplesToRead);
  181. pjmedia_circ_buf_read(inputBuff, samples, samplesToRead);
  182. if (availableSamples < count) {
  183. pjsuaLogger.debug("Requested %d samples, available %d, filling remaining with zeros.", count,
  184. availableSamples);
  185. for (int i = samplesToRead; i < count; ++i) {
  186. samples[i] = 0;
  187. }
  188. }
  189. return PJ_SUCCESS;
  190. }
  191. pj_status_t sip::PjsuaCommunicator::mediaPortPutFrame(pjmedia_port *port, pjmedia_frame *frame) {
  192. pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
  193. pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&port->info);
  194. frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
  195. if (count > 0) {
  196. pjsuaLogger.debug("Calling onIncomingPcmSamples with %d samples.", count);
  197. onIncomingPcmSamples(samples, count);
  198. }
  199. return PJ_SUCCESS;
  200. }
  201. void sip::PjsuaCommunicator::registerAccount(string host, string user, string password) {
  202. string uri = "sip:" + user + "@" + host;
  203. pj::AccountConfig accountConfig;
  204. accountConfig.idUri = uri;
  205. accountConfig.regConfig.registrarUri = "sip:" + host;
  206. pj::AuthCredInfo cred("digest", "*", user, 0, password);
  207. accountConfig.sipConfig.authCreds.push_back(cred);
  208. logger.info("Registering account for URI: %s.", uri.c_str());
  209. account.reset(new _Account(*this));
  210. account->create(accountConfig);
  211. }
  212. void sip::PjsuaCommunicator::sendPcmSamples(int16_t *samples, unsigned int length) {
  213. std::unique_lock<std::mutex> lock(inBuffAccessMutex);
  214. pjsuaLogger.debug("Pushing %d samples to in-buff.", length);
  215. pjmedia_circ_buf_write(inputBuff, samples, length);
  216. }