websocket-server.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. websocketpp::lib::mutex& thread_lock,
  50. std::vector<std::vector<float>> &hotwords_embedding,
  51. std::string wav_name,
  52. std::string wav_format) {
  53. scoped_lock guard(thread_lock);
  54. try {
  55. int num_samples = buffer.size(); // the size of the buf
  56. if (!buffer.empty() && hotwords_embedding.size() >0 ) {
  57. std::string asr_result;
  58. std::string stamp_res;
  59. try{
  60. FUNASR_RESULT Result = FunOfflineInferBuffer(
  61. asr_hanlde, buffer.data(), buffer.size(), RASR_NONE, NULL, hotwords_embedding, 16000, wav_format);
  62. asr_result = ((FUNASR_RECOG_RESULT*)Result)->msg; // get decode result
  63. stamp_res = ((FUNASR_RECOG_RESULT*)Result)->stamp;
  64. FunASRFreeResult(Result);
  65. }catch (std::exception const& e) {
  66. LOG(ERROR) << e.what();
  67. return;
  68. }
  69. websocketpp::lib::error_code ec;
  70. nlohmann::json jsonresult; // result json
  71. jsonresult["text"] = asr_result; // put result in 'text'
  72. jsonresult["mode"] = "offline";
  73. jsonresult["is_final"] = false;
  74. if(stamp_res != ""){
  75. jsonresult["timestamp"] = stamp_res;
  76. }
  77. jsonresult["wav_name"] = wav_name;
  78. // send the json to client
  79. if (is_ssl) {
  80. wss_server_->send(hdl, jsonresult.dump(),
  81. websocketpp::frame::opcode::text, ec);
  82. } else {
  83. server_->send(hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  84. ec);
  85. }
  86. LOG(INFO) << "buffer.size=" << buffer.size() << ",result json=" << jsonresult.dump();
  87. }else{
  88. websocketpp::lib::error_code ec;
  89. nlohmann::json jsonresult; // result json
  90. jsonresult["text"] = ""; // put result in 'text'
  91. jsonresult["mode"] = "offline";
  92. jsonresult["is_final"] = false;
  93. jsonresult["wav_name"] = wav_name;
  94. // send the json to client
  95. if (is_ssl) {
  96. wss_server_->send(hdl, jsonresult.dump(),
  97. websocketpp::frame::opcode::text, ec);
  98. } else {
  99. server_->send(hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  100. ec);
  101. }
  102. }
  103. } catch (std::exception const& e) {
  104. std::cerr << "Error: " << e.what() << std::endl;
  105. }
  106. }
  107. void WebSocketServer::on_open(websocketpp::connection_hdl hdl) {
  108. scoped_lock guard(m_lock); // for threads safty
  109. std::shared_ptr<FUNASR_MESSAGE> data_msg =
  110. std::make_shared<FUNASR_MESSAGE>(); // put a new data vector for new
  111. // connection
  112. data_msg->samples = std::make_shared<std::vector<char>>();
  113. data_msg->thread_lock = std::make_shared<websocketpp::lib::mutex>();
  114. data_msg->msg = nlohmann::json::parse("{}");
  115. data_msg->msg["wav_format"] = "pcm";
  116. data_map.emplace(hdl, data_msg);
  117. LOG(INFO) << "on_open, active connections: " << data_map.size();
  118. }
  119. void WebSocketServer::on_close(websocketpp::connection_hdl hdl) {
  120. scoped_lock guard(m_lock);
  121. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  122. auto it_data = data_map.find(hdl);
  123. if (it_data != data_map.end()) {
  124. data_msg = it_data->second;
  125. } else {
  126. return;
  127. }
  128. unique_lock guard_decoder(*(data_msg->thread_lock));
  129. data_msg->msg["is_eof"]=true;
  130. guard_decoder.unlock();
  131. // data_map.erase(hdl); // remove data vector when connection is closed
  132. LOG(INFO) << "on_close, active connections: " << data_map.size();
  133. }
  134. void remove_hdl(
  135. websocketpp::connection_hdl hdl,
  136. std::map<websocketpp::connection_hdl, std::shared_ptr<FUNASR_MESSAGE>,
  137. std::owner_less<websocketpp::connection_hdl>>& data_map) {
  138. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  139. auto it_data = data_map.find(hdl);
  140. if (it_data != data_map.end()) {
  141. data_msg = it_data->second;
  142. } else {
  143. return;
  144. }
  145. unique_lock guard_decoder(*(data_msg->thread_lock));
  146. if (data_msg->msg["is_eof"]==true) {
  147. data_map.erase(hdl);
  148. LOG(INFO) << "remove one connection";
  149. }
  150. guard_decoder.unlock();
  151. }
  152. void WebSocketServer::check_and_clean_connection() {
  153. while(true){
  154. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  155. std::vector<websocketpp::connection_hdl> to_remove; // remove list
  156. auto iter = data_map.begin();
  157. while (iter != data_map.end()) { // loop to find closed connection
  158. websocketpp::connection_hdl hdl = iter->first;
  159. try{
  160. if (is_ssl) {
  161. wss_server::connection_ptr con = wss_server_->get_con_from_hdl(hdl);
  162. if (con->get_state() != 1) { // session::state::open ==1
  163. to_remove.push_back(hdl);
  164. }
  165. } else {
  166. server::connection_ptr con = server_->get_con_from_hdl(hdl);
  167. if (con->get_state() != 1) { // session::state::open ==1
  168. to_remove.push_back(hdl);
  169. }
  170. }
  171. }
  172. catch (std::exception const &e)
  173. {
  174. // if connection is close, we set is_eof = true
  175. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  176. auto it_data = data_map.find(hdl);
  177. if (it_data != data_map.end()) {
  178. data_msg = it_data->second;
  179. } else {
  180. continue;
  181. }
  182. unique_lock guard_decoder(*(data_msg->thread_lock));
  183. data_msg->msg["is_eof"]=true;
  184. guard_decoder.unlock();
  185. to_remove.push_back(hdl);
  186. LOG(INFO)<<"connection is closed: "<<e.what();
  187. }
  188. iter++;
  189. }
  190. for (auto hdl : to_remove) {
  191. remove_hdl(hdl, data_map);
  192. //LOG(INFO) << "remove one connection ";
  193. }
  194. }
  195. }
  196. void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
  197. message_ptr msg) {
  198. unique_lock lock(m_lock);
  199. // find the sample data vector according to one connection
  200. std::shared_ptr<FUNASR_MESSAGE> msg_data = nullptr;
  201. auto it_data = data_map.find(hdl);
  202. if (it_data != data_map.end()) {
  203. msg_data = it_data->second;
  204. }
  205. std::shared_ptr<std::vector<char>> sample_data_p = msg_data->samples;
  206. std::shared_ptr<websocketpp::lib::mutex> thread_lock_p = msg_data->thread_lock;
  207. lock.unlock();
  208. if (sample_data_p == nullptr) {
  209. LOG(INFO) << "error when fetch sample data vector";
  210. return;
  211. }
  212. const std::string& payload = msg->get_payload(); // get msg type
  213. unique_lock guard_decoder(*(thread_lock_p)); // mutex for one connection
  214. switch (msg->get_opcode()) {
  215. case websocketpp::frame::opcode::text: {
  216. nlohmann::json jsonresult = nlohmann::json::parse(payload);
  217. if (jsonresult["wav_name"] != nullptr) {
  218. msg_data->msg["wav_name"] = jsonresult["wav_name"];
  219. }
  220. if (jsonresult["wav_format"] != nullptr) {
  221. msg_data->msg["wav_format"] = jsonresult["wav_format"];
  222. }
  223. if(msg_data->hotwords_embedding == NULL){
  224. if (jsonresult["hotwords"] != nullptr) {
  225. msg_data->msg["hotwords"] = jsonresult["hotwords"];
  226. if (!msg_data->msg["hotwords"].empty()) {
  227. std::string hw = msg_data->msg["hotwords"];
  228. LOG(INFO)<<"hotwords: " << hw;
  229. std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_hanlde, hw);
  230. msg_data->hotwords_embedding =
  231. std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
  232. }
  233. }else{
  234. std::string hw = "";
  235. LOG(INFO)<<"hotwords: " << hw;
  236. std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_hanlde, hw);
  237. msg_data->hotwords_embedding =
  238. std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
  239. }
  240. }
  241. if (jsonresult["is_speaking"] == false ||
  242. jsonresult["is_finished"] == true) {
  243. LOG(INFO) << "client done";
  244. // add padding to the end of the wav data
  245. // std::vector<short> padding(static_cast<short>(0.3 * 16000));
  246. // sample_data_p->insert(sample_data_p->end(), padding.data(),
  247. // padding.data() + padding.size());
  248. // for offline, send all receive data to decoder engine
  249. std::vector<std::vector<float>> hotwords_embedding_(*(msg_data->hotwords_embedding));
  250. asio::post(io_decoder_,
  251. std::bind(&WebSocketServer::do_decoder, this,
  252. std::move(*(sample_data_p.get())),
  253. std::move(hdl),
  254. std::ref(*thread_lock_p),
  255. std::move(hotwords_embedding_),
  256. msg_data->msg["wav_name"],
  257. msg_data->msg["wav_format"]));
  258. }
  259. break;
  260. }
  261. case websocketpp::frame::opcode::binary: {
  262. // recived binary data
  263. const auto* pcm_data = static_cast<const char*>(payload.data());
  264. int32_t num_samples = payload.size();
  265. //LOG(INFO) << "recv binary num_samples " << num_samples;
  266. if (isonline) {
  267. // TODO
  268. } else {
  269. // for offline, we add receive data to end of the sample data vector
  270. sample_data_p->insert(sample_data_p->end(), pcm_data,
  271. pcm_data + num_samples);
  272. }
  273. break;
  274. }
  275. default:
  276. break;
  277. }
  278. }
  279. // init asr model
  280. void WebSocketServer::initAsr(std::map<std::string, std::string>& model_path,
  281. int thread_num) {
  282. try {
  283. // init model with api
  284. asr_hanlde = FunOfflineInit(model_path, thread_num);
  285. LOG(INFO) << "model successfully inited";
  286. LOG(INFO) << "initAsr run check_and_clean_connection";
  287. std::thread clean_thread(&WebSocketServer::check_and_clean_connection,this);
  288. clean_thread.detach();
  289. LOG(INFO) << "initAsr run check_and_clean_connection finished";
  290. } catch (const std::exception& e) {
  291. LOG(INFO) << e.what();
  292. }
  293. }