websocket-server.cpp 12 KB

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