websocket-server.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /**
  2. * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights
  3. * Reserved. MIT License (https://opensource.org/licenses/MIT)
  4. */
  5. /* 2022-2023 by zhaomingwork */
  6. // websocket server for asr engine
  7. // take some ideas from https://github.com/k2-fsa/sherpa-onnx
  8. // online-websocket-server-impl.cc, thanks. The websocket server has two threads
  9. // pools, one for handle network data and one for asr decoder.
  10. // now only support offline engine.
  11. #include "websocket-server.h"
  12. #include <thread>
  13. #include <utility>
  14. #include <vector>
  15. context_ptr WebSocketServer::on_tls_init(tls_mode mode,
  16. websocketpp::connection_hdl hdl,
  17. std::string& s_certfile,
  18. std::string& s_keyfile) {
  19. namespace asio = websocketpp::lib::asio;
  20. LOG(INFO) << "on_tls_init called with hdl: " << hdl.lock().get();
  21. LOG(INFO) << "using TLS mode: "
  22. << (mode == MOZILLA_MODERN ? "Mozilla Modern"
  23. : "Mozilla Intermediate");
  24. context_ptr ctx = websocketpp::lib::make_shared<asio::ssl::context>(
  25. asio::ssl::context::sslv23);
  26. try {
  27. if (mode == MOZILLA_MODERN) {
  28. // Modern disables TLSv1
  29. ctx->set_options(
  30. asio::ssl::context::default_workarounds |
  31. asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3 |
  32. asio::ssl::context::no_tlsv1 | asio::ssl::context::single_dh_use);
  33. } else {
  34. ctx->set_options(asio::ssl::context::default_workarounds |
  35. asio::ssl::context::no_sslv2 |
  36. asio::ssl::context::no_sslv3 |
  37. asio::ssl::context::single_dh_use);
  38. }
  39. ctx->use_certificate_chain_file(s_certfile);
  40. ctx->use_private_key_file(s_keyfile, asio::ssl::context::pem);
  41. } catch (std::exception& e) {
  42. LOG(INFO) << "Exception: " << e.what();
  43. }
  44. return ctx;
  45. }
  46. // feed buffer to asr engine for decoder
  47. void WebSocketServer::do_decoder(const std::vector<char>& buffer,
  48. websocketpp::connection_hdl& hdl,
  49. const nlohmann::json& msg) {
  50. try {
  51. int num_samples = buffer.size(); // the size of the buf
  52. if (!buffer.empty()) {
  53. // fout.write(buffer.data(), buffer.size());
  54. // feed data to asr engine
  55. FUNASR_RESULT Result = FunOfflineInferBuffer(
  56. asr_hanlde, buffer.data(), buffer.size(), RASR_NONE, NULL, 16000);
  57. std::string asr_result =
  58. ((FUNASR_RECOG_RESULT*)Result)->msg; // get decode result
  59. websocketpp::lib::error_code ec;
  60. nlohmann::json jsonresult; // result json
  61. jsonresult["text"] = asr_result; // put result in 'text'
  62. jsonresult["mode"] = "offline";
  63. jsonresult["wav_name"] = msg["wav_name"];
  64. // send the json to client
  65. if (is_ssl) {
  66. wss_server_->send(hdl, jsonresult.dump(),
  67. websocketpp::frame::opcode::text, ec);
  68. } else {
  69. server_->send(hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  70. ec);
  71. }
  72. LOG(INFO) << "buffer.size=" << buffer.size() << ",result json=" << jsonresult.dump();
  73. if (!isonline) {
  74. // close the client if it is not online asr
  75. // server_->close(hdl, websocketpp::close::status::normal, "DONE", ec);
  76. // fout.close();
  77. }
  78. }
  79. } catch (std::exception const& e) {
  80. std::cerr << "Error: " << e.what() << std::endl;
  81. }
  82. }
  83. void WebSocketServer::on_open(websocketpp::connection_hdl hdl) {
  84. scoped_lock guard(m_lock); // for threads safty
  85. check_and_clean_connection(); // remove closed connection
  86. std::shared_ptr<FUNASR_MESSAGE> data_msg =
  87. std::make_shared<FUNASR_MESSAGE>(); // put a new data vector for new
  88. // connection
  89. data_msg->samples = std::make_shared<std::vector<char>>();
  90. data_msg->msg = nlohmann::json::parse("{}");
  91. data_map.emplace(hdl, data_msg);
  92. LOG(INFO) << "on_open, active connections: " << data_map.size();
  93. }
  94. void WebSocketServer::on_close(websocketpp::connection_hdl hdl) {
  95. scoped_lock guard(m_lock);
  96. data_map.erase(hdl); // remove data vector when connection is closed
  97. LOG(INFO) << "on_close, active connections: " << data_map.size();
  98. }
  99. // remove closed connection
  100. void WebSocketServer::check_and_clean_connection() {
  101. std::vector<websocketpp::connection_hdl> to_remove; // remove list
  102. auto iter = data_map.begin();
  103. while (iter != data_map.end()) { // loop to find closed connection
  104. websocketpp::connection_hdl hdl = iter->first;
  105. if (is_ssl) {
  106. wss_server::connection_ptr con = wss_server_->get_con_from_hdl(hdl);
  107. if (con->get_state() != 1) { // session::state::open ==1
  108. to_remove.push_back(hdl);
  109. }
  110. } else {
  111. server::connection_ptr con = server_->get_con_from_hdl(hdl);
  112. if (con->get_state() != 1) { // session::state::open ==1
  113. to_remove.push_back(hdl);
  114. }
  115. }
  116. iter++;
  117. }
  118. for (auto hdl : to_remove) {
  119. data_map.erase(hdl);
  120. LOG(INFO)<< "remove one connection ";
  121. }
  122. }
  123. void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
  124. message_ptr msg) {
  125. unique_lock lock(m_lock);
  126. // find the sample data vector according to one connection
  127. std::shared_ptr<FUNASR_MESSAGE> msg_data = nullptr;
  128. auto it_data = data_map.find(hdl);
  129. if (it_data != data_map.end()) {
  130. msg_data = it_data->second;
  131. }
  132. std::shared_ptr<std::vector<char>> sample_data_p = msg_data->samples;
  133. lock.unlock();
  134. if (sample_data_p == nullptr) {
  135. LOG(INFO) << "error when fetch sample data vector";
  136. return;
  137. }
  138. const std::string& payload = msg->get_payload(); // get msg type
  139. switch (msg->get_opcode()) {
  140. case websocketpp::frame::opcode::text: {
  141. nlohmann::json jsonresult = nlohmann::json::parse(payload);
  142. if (jsonresult["wav_name"] != nullptr) {
  143. msg_data->msg["wav_name"] = jsonresult["wav_name"];
  144. }
  145. if (jsonresult["is_speaking"] == false ||
  146. jsonresult["is_finished"] == true) {
  147. LOG(INFO) << "client done";
  148. if (isonline) {
  149. // do_close(ws);
  150. } else {
  151. // add padding to the end of the wav data
  152. std::vector<short> padding(static_cast<short>(0.3 * 16000));
  153. sample_data_p->insert(sample_data_p->end(), padding.data(),
  154. padding.data() + padding.size());
  155. // for offline, send all receive data to decoder engine
  156. asio::post(io_decoder_,
  157. std::bind(&WebSocketServer::do_decoder, this,
  158. std::move(*(sample_data_p.get())),
  159. std::move(hdl), std::move(msg_data->msg)));
  160. }
  161. }
  162. break;
  163. }
  164. case websocketpp::frame::opcode::binary: {
  165. // recived binary data
  166. const auto* pcm_data = static_cast<const char*>(payload.data());
  167. int32_t num_samples = payload.size();
  168. if (isonline) {
  169. // if online TODO(zhaoming) still not done
  170. std::vector<char> s(pcm_data, pcm_data + num_samples);
  171. asio::post(io_decoder_,
  172. std::bind(&WebSocketServer::do_decoder, this, std::move(s),
  173. std::move(hdl), std::move(msg_data->msg)));
  174. } else {
  175. // for offline, we add receive data to end of the sample data vector
  176. sample_data_p->insert(sample_data_p->end(), pcm_data,
  177. pcm_data + num_samples);
  178. }
  179. break;
  180. }
  181. default:
  182. break;
  183. }
  184. }
  185. // init asr model
  186. void WebSocketServer::initAsr(std::map<std::string, std::string>& model_path,
  187. int thread_num) {
  188. try {
  189. // init model with api
  190. asr_hanlde = FunOfflineInit(model_path, thread_num);
  191. LOG(INFO) << "model successfully inited";
  192. } catch (const std::exception& e) {
  193. LOG(INFO) << e.what();
  194. }
  195. }