websocket-server.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. LOG(INFO) << "Sent empty meg";
  89. websocketpp::lib::error_code ec;
  90. nlohmann::json jsonresult; // result json
  91. jsonresult["text"] = ""; // put result in 'text'
  92. jsonresult["mode"] = "offline";
  93. jsonresult["is_final"] = false;
  94. jsonresult["wav_name"] = wav_name;
  95. // send the json to client
  96. if (is_ssl) {
  97. wss_server_->send(hdl, jsonresult.dump(),
  98. websocketpp::frame::opcode::text, ec);
  99. } else {
  100. server_->send(hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  101. ec);
  102. }
  103. }
  104. } catch (std::exception const& e) {
  105. std::cerr << "Error: " << e.what() << std::endl;
  106. }
  107. }
  108. void WebSocketServer::on_open(websocketpp::connection_hdl hdl) {
  109. scoped_lock guard(m_lock); // for threads safty
  110. std::shared_ptr<FUNASR_MESSAGE> data_msg =
  111. std::make_shared<FUNASR_MESSAGE>(); // put a new data vector for new
  112. // connection
  113. data_msg->samples = std::make_shared<std::vector<char>>();
  114. data_msg->thread_lock = std::make_shared<websocketpp::lib::mutex>();
  115. data_msg->msg = nlohmann::json::parse("{}");
  116. data_msg->msg["wav_format"] = "pcm";
  117. data_map.emplace(hdl, data_msg);
  118. LOG(INFO) << "on_open, active connections: " << data_map.size();
  119. }
  120. void WebSocketServer::on_close(websocketpp::connection_hdl hdl) {
  121. scoped_lock guard(m_lock);
  122. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  123. auto it_data = data_map.find(hdl);
  124. if (it_data != data_map.end()) {
  125. data_msg = it_data->second;
  126. } else {
  127. return;
  128. }
  129. unique_lock guard_decoder(*(data_msg->thread_lock));
  130. data_msg->msg["is_eof"]=true;
  131. guard_decoder.unlock();
  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. {
  192. unique_lock lock(m_lock);
  193. remove_hdl(hdl, data_map);
  194. }
  195. }
  196. }
  197. }
  198. void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
  199. message_ptr msg) {
  200. unique_lock lock(m_lock);
  201. // find the sample data vector according to one connection
  202. std::shared_ptr<FUNASR_MESSAGE> msg_data = nullptr;
  203. auto it_data = data_map.find(hdl);
  204. if (it_data != data_map.end()) {
  205. msg_data = it_data->second;
  206. } else{
  207. lock.unlock();
  208. return;
  209. }
  210. std::shared_ptr<std::vector<char>> sample_data_p = msg_data->samples;
  211. std::shared_ptr<websocketpp::lib::mutex> thread_lock_p = msg_data->thread_lock;
  212. lock.unlock();
  213. if (sample_data_p == nullptr) {
  214. LOG(INFO) << "error when fetch sample data vector";
  215. return;
  216. }
  217. const std::string& payload = msg->get_payload(); // get msg type
  218. unique_lock guard_decoder(*(thread_lock_p)); // mutex for one connection
  219. switch (msg->get_opcode()) {
  220. case websocketpp::frame::opcode::text: {
  221. nlohmann::json jsonresult = nlohmann::json::parse(payload);
  222. if (jsonresult["wav_name"] != nullptr) {
  223. msg_data->msg["wav_name"] = jsonresult["wav_name"];
  224. }
  225. if (jsonresult["wav_format"] != nullptr) {
  226. msg_data->msg["wav_format"] = jsonresult["wav_format"];
  227. }
  228. if(msg_data->hotwords_embedding == NULL){
  229. if (jsonresult["hotwords"] != nullptr) {
  230. msg_data->msg["hotwords"] = jsonresult["hotwords"];
  231. if (!msg_data->msg["hotwords"].empty()) {
  232. std::string hw = msg_data->msg["hotwords"];
  233. LOG(INFO)<<"hotwords: " << hw;
  234. std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_hanlde, hw);
  235. msg_data->hotwords_embedding =
  236. std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
  237. }
  238. }else{
  239. std::string hw = "";
  240. LOG(INFO)<<"hotwords: " << hw;
  241. std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_hanlde, hw);
  242. msg_data->hotwords_embedding =
  243. std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
  244. }
  245. }
  246. if (jsonresult["is_speaking"] == false ||
  247. jsonresult["is_finished"] == true) {
  248. LOG(INFO) << "client done";
  249. // add padding to the end of the wav data
  250. // std::vector<short> padding(static_cast<short>(0.3 * 16000));
  251. // sample_data_p->insert(sample_data_p->end(), padding.data(),
  252. // padding.data() + padding.size());
  253. // for offline, send all receive data to decoder engine
  254. std::vector<std::vector<float>> hotwords_embedding_(*(msg_data->hotwords_embedding));
  255. asio::post(io_decoder_,
  256. std::bind(&WebSocketServer::do_decoder, this,
  257. std::move(*(sample_data_p.get())),
  258. std::move(hdl),
  259. std::ref(*thread_lock_p),
  260. std::move(hotwords_embedding_),
  261. msg_data->msg["wav_name"],
  262. msg_data->msg["wav_format"]));
  263. }
  264. break;
  265. }
  266. case websocketpp::frame::opcode::binary: {
  267. // recived binary data
  268. const auto* pcm_data = static_cast<const char*>(payload.data());
  269. int32_t num_samples = payload.size();
  270. //LOG(INFO) << "recv binary num_samples " << num_samples;
  271. if (isonline) {
  272. // TODO
  273. } else {
  274. // for offline, we add receive data to end of the sample data vector
  275. sample_data_p->insert(sample_data_p->end(), pcm_data,
  276. pcm_data + num_samples);
  277. }
  278. break;
  279. }
  280. default:
  281. break;
  282. }
  283. }
  284. // init asr model
  285. void WebSocketServer::initAsr(std::map<std::string, std::string>& model_path,
  286. int thread_num) {
  287. try {
  288. // init model with api
  289. asr_hanlde = FunOfflineInit(model_path, thread_num);
  290. LOG(INFO) << "model successfully inited";
  291. LOG(INFO) << "initAsr run check_and_clean_connection";
  292. std::thread clean_thread(&WebSocketServer::check_and_clean_connection,this);
  293. clean_thread.detach();
  294. LOG(INFO) << "initAsr run check_and_clean_connection finished";
  295. } catch (const std::exception& e) {
  296. LOG(INFO) << e.what();
  297. }
  298. }