websocket-server.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. extern std::unordered_map<std::string, int> hws_map_;
  16. extern int fst_inc_wts_;
  17. extern float global_beam_, lattice_beam_, am_scale_;
  18. context_ptr WebSocketServer::on_tls_init(tls_mode mode,
  19. websocketpp::connection_hdl hdl,
  20. std::string& s_certfile,
  21. std::string& s_keyfile) {
  22. namespace asio = websocketpp::lib::asio;
  23. LOG(INFO) << "on_tls_init called with hdl: " << hdl.lock().get();
  24. LOG(INFO) << "using TLS mode: "
  25. << (mode == MOZILLA_MODERN ? "Mozilla Modern"
  26. : "Mozilla Intermediate");
  27. context_ptr ctx = websocketpp::lib::make_shared<asio::ssl::context>(
  28. asio::ssl::context::sslv23);
  29. try {
  30. if (mode == MOZILLA_MODERN) {
  31. // Modern disables TLSv1
  32. ctx->set_options(
  33. asio::ssl::context::default_workarounds |
  34. asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3 |
  35. asio::ssl::context::no_tlsv1 | asio::ssl::context::single_dh_use);
  36. } else {
  37. ctx->set_options(asio::ssl::context::default_workarounds |
  38. asio::ssl::context::no_sslv2 |
  39. asio::ssl::context::no_sslv3 |
  40. asio::ssl::context::single_dh_use);
  41. }
  42. ctx->use_certificate_chain_file(s_certfile);
  43. ctx->use_private_key_file(s_keyfile, asio::ssl::context::pem);
  44. } catch (std::exception& e) {
  45. LOG(INFO) << "Exception: " << e.what();
  46. }
  47. return ctx;
  48. }
  49. // feed buffer to asr engine for decoder
  50. void WebSocketServer::do_decoder(const std::vector<char>& buffer,
  51. websocketpp::connection_hdl& hdl,
  52. nlohmann::json& msg,
  53. websocketpp::lib::mutex& thread_lock,
  54. std::vector<std::vector<float>> &hotwords_embedding,
  55. std::string wav_name,
  56. bool itn,
  57. int audio_fs,
  58. std::string wav_format,
  59. FUNASR_DEC_HANDLE& decoder_handle) {
  60. scoped_lock guard(thread_lock);
  61. try {
  62. int num_samples = buffer.size(); // the size of the buf
  63. if (!buffer.empty() && hotwords_embedding.size() > 0) {
  64. std::string asr_result;
  65. std::string stamp_res;
  66. try{
  67. FUNASR_RESULT Result = FunOfflineInferBuffer(
  68. asr_handle, buffer.data(), buffer.size(), RASR_NONE, NULL,
  69. hotwords_embedding, audio_fs, wav_format, itn, decoder_handle);
  70. asr_result = ((FUNASR_RECOG_RESULT*)Result)->msg; // get decode result
  71. stamp_res = ((FUNASR_RECOG_RESULT*)Result)->stamp;
  72. FunASRFreeResult(Result);
  73. }catch (std::exception const& e) {
  74. LOG(ERROR) << e.what();
  75. return;
  76. }
  77. websocketpp::lib::error_code ec;
  78. nlohmann::json jsonresult; // result json
  79. jsonresult["text"] = asr_result; // put result in 'text'
  80. jsonresult["mode"] = "offline";
  81. jsonresult["is_final"] = false;
  82. if(stamp_res != ""){
  83. jsonresult["timestamp"] = stamp_res;
  84. }
  85. jsonresult["wav_name"] = wav_name;
  86. // send the json to client
  87. if (is_ssl) {
  88. wss_server_->send(hdl, jsonresult.dump(),
  89. websocketpp::frame::opcode::text, ec);
  90. } else {
  91. server_->send(hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  92. ec);
  93. }
  94. LOG(INFO) << "buffer.size=" << buffer.size() << ",result json=" << jsonresult.dump();
  95. }else{
  96. LOG(INFO) << "Sent empty msg";
  97. websocketpp::lib::error_code ec;
  98. nlohmann::json jsonresult; // result json
  99. jsonresult["text"] = ""; // put result in 'text'
  100. jsonresult["mode"] = "offline";
  101. jsonresult["is_final"] = false;
  102. jsonresult["wav_name"] = wav_name;
  103. // send the json to client
  104. if (is_ssl) {
  105. wss_server_->send(hdl, jsonresult.dump(),
  106. websocketpp::frame::opcode::text, ec);
  107. } else {
  108. server_->send(hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  109. ec);
  110. }
  111. }
  112. } catch (std::exception const& e) {
  113. std::cerr << "Error: " << e.what() << std::endl;
  114. }
  115. msg["access_num"]=(int)msg["access_num"]-1;
  116. }
  117. void WebSocketServer::on_open(websocketpp::connection_hdl hdl) {
  118. scoped_lock guard(m_lock); // for threads safty
  119. std::shared_ptr<FUNASR_MESSAGE> data_msg =
  120. std::make_shared<FUNASR_MESSAGE>(); // put a new data vector for new
  121. // connection
  122. data_msg->samples = std::make_shared<std::vector<char>>();
  123. data_msg->thread_lock = std::make_shared<websocketpp::lib::mutex>();
  124. data_msg->msg = nlohmann::json::parse("{}");
  125. data_msg->msg["wav_format"] = "pcm";
  126. data_msg->msg["wav_name"] = "wav-default-id";
  127. data_msg->msg["itn"] = true;
  128. data_msg->msg["audio_fs"] = 16000;
  129. data_msg->msg["access_num"] = 0; // the number of access for this object, when it is 0, we can free it saftly
  130. FUNASR_DEC_HANDLE decoder_handle =
  131. FunASRWfstDecoderInit(asr_handle, ASR_OFFLINE, global_beam_, lattice_beam_, am_scale_);
  132. data_msg->decoder_handle = decoder_handle;
  133. data_map.emplace(hdl, data_msg);
  134. LOG(INFO) << "on_open, active connections: " << data_map.size();
  135. }
  136. void WebSocketServer::on_close(websocketpp::connection_hdl hdl) {
  137. scoped_lock guard(m_lock);
  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. data_msg->msg["is_eof"]=true;
  147. guard_decoder.unlock();
  148. LOG(INFO) << "on_close, active connections: " << data_map.size();
  149. }
  150. void remove_hdl(
  151. websocketpp::connection_hdl hdl,
  152. std::map<websocketpp::connection_hdl, std::shared_ptr<FUNASR_MESSAGE>,
  153. std::owner_less<websocketpp::connection_hdl>>& data_map) {
  154. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  155. auto it_data = data_map.find(hdl);
  156. if (it_data != data_map.end()) {
  157. data_msg = it_data->second;
  158. } else {
  159. return;
  160. }
  161. unique_lock guard_decoder(*(data_msg->thread_lock));
  162. if (data_msg->msg["access_num"]==0 && data_msg->msg["is_eof"]==true) {
  163. FunWfstDecoderUnloadHwsRes(data_msg->decoder_handle);
  164. FunASRWfstDecoderUninit(data_msg->decoder_handle);
  165. data_msg->decoder_handle = nullptr;
  166. data_map.erase(hdl);
  167. LOG(INFO) << "remove one connection";
  168. }
  169. guard_decoder.unlock();
  170. }
  171. void WebSocketServer::check_and_clean_connection() {
  172. while(true){
  173. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  174. std::vector<websocketpp::connection_hdl> to_remove; // remove list
  175. auto iter = data_map.begin();
  176. while (iter != data_map.end()) { // loop to find closed connection
  177. websocketpp::connection_hdl hdl = iter->first;
  178. try{
  179. if (is_ssl) {
  180. wss_server::connection_ptr con = wss_server_->get_con_from_hdl(hdl);
  181. if (con->get_state() != 1) { // session::state::open ==1
  182. to_remove.push_back(hdl);
  183. }
  184. } else {
  185. server::connection_ptr con = server_->get_con_from_hdl(hdl);
  186. if (con->get_state() != 1) { // session::state::open ==1
  187. to_remove.push_back(hdl);
  188. }
  189. }
  190. }
  191. catch (std::exception const &e)
  192. {
  193. // if connection is close, we set is_eof = true
  194. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  195. auto it_data = data_map.find(hdl);
  196. if (it_data != data_map.end()) {
  197. data_msg = it_data->second;
  198. } else {
  199. continue;
  200. }
  201. unique_lock guard_decoder(*(data_msg->thread_lock));
  202. data_msg->msg["is_eof"]=true;
  203. guard_decoder.unlock();
  204. to_remove.push_back(hdl);
  205. LOG(INFO)<<"connection is closed: "<<e.what();
  206. }
  207. iter++;
  208. }
  209. for (auto hdl : to_remove) {
  210. {
  211. unique_lock lock(m_lock);
  212. remove_hdl(hdl, data_map);
  213. }
  214. }
  215. }
  216. }
  217. void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
  218. message_ptr msg) {
  219. unique_lock lock(m_lock);
  220. // find the sample data vector according to one connection
  221. std::shared_ptr<FUNASR_MESSAGE> msg_data = nullptr;
  222. auto it_data = data_map.find(hdl);
  223. if (it_data != data_map.end()) {
  224. msg_data = it_data->second;
  225. } else{
  226. lock.unlock();
  227. return;
  228. }
  229. std::shared_ptr<std::vector<char>> sample_data_p = msg_data->samples;
  230. std::shared_ptr<websocketpp::lib::mutex> thread_lock_p = msg_data->thread_lock;
  231. lock.unlock();
  232. if (sample_data_p == nullptr) {
  233. LOG(INFO) << "error when fetch sample data vector";
  234. return;
  235. }
  236. const std::string& payload = msg->get_payload(); // get msg type
  237. unique_lock guard_decoder(*(thread_lock_p)); // mutex for one connection
  238. switch (msg->get_opcode()) {
  239. case websocketpp::frame::opcode::text: {
  240. nlohmann::json jsonresult;
  241. try{
  242. jsonresult = nlohmann::json::parse(payload);
  243. }catch (std::exception const &e)
  244. {
  245. LOG(ERROR)<<e.what();
  246. break;
  247. }
  248. if (jsonresult["wav_name"] != nullptr) {
  249. msg_data->msg["wav_name"] = jsonresult["wav_name"];
  250. }
  251. if (jsonresult["wav_format"] != nullptr) {
  252. msg_data->msg["wav_format"] = jsonresult["wav_format"];
  253. }
  254. // hotwords: fst/nn
  255. if(msg_data->hotwords_embedding == NULL){
  256. std::unordered_map<std::string, int> merged_hws_map;
  257. std::string nn_hotwords = "";
  258. if (jsonresult["hotwords"] != nullptr) {
  259. std::string json_string = jsonresult["hotwords"];
  260. if (!json_string.empty()){
  261. nlohmann::json json_fst_hws;
  262. try{
  263. json_fst_hws = nlohmann::json::parse(json_string);
  264. } catch (std::exception const &e)
  265. {
  266. LOG(ERROR)<<e.what();
  267. break;
  268. }
  269. if(json_fst_hws.type() == nlohmann::json::value_t::object){
  270. // fst
  271. try{
  272. std::unordered_map<std::string, int> client_hws_map = json_fst_hws;
  273. merged_hws_map.insert(client_hws_map.begin(), client_hws_map.end());
  274. } catch (const std::exception& e) {
  275. LOG(INFO) << e.what();
  276. }
  277. }else{
  278. // nn
  279. std::string client_nn_hws = jsonresult["hotwords"];
  280. nn_hotwords += " " + client_nn_hws;
  281. LOG(INFO) << "nn hotwords: " << client_nn_hws;
  282. }
  283. }
  284. }
  285. merged_hws_map.insert(hws_map_.begin(), hws_map_.end());
  286. // fst
  287. LOG(INFO) << "hotwords: ";
  288. for (const auto& pair : merged_hws_map) {
  289. nn_hotwords += " " + pair.first;
  290. LOG(INFO) << pair.first << " : " << pair.second;
  291. }
  292. FunWfstDecoderLoadHwsRes(msg_data->decoder_handle, fst_inc_wts_, merged_hws_map);
  293. // nn
  294. std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_handle, nn_hotwords);
  295. msg_data->hotwords_embedding =
  296. std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
  297. }
  298. if (jsonresult.contains("audio_fs")) {
  299. msg_data->msg["audio_fs"] = jsonresult["audio_fs"];
  300. }
  301. if (jsonresult.contains("itn")) {
  302. msg_data->msg["itn"] = jsonresult["itn"];
  303. }
  304. if (jsonresult["is_speaking"] == false ||
  305. jsonresult["is_finished"] == true) {
  306. LOG(INFO) << "client done";
  307. // for offline, send all receive data to decoder engine
  308. std::vector<std::vector<float>> hotwords_embedding_(*(msg_data->hotwords_embedding));
  309. asio::post(io_decoder_,
  310. std::bind(&WebSocketServer::do_decoder, this,
  311. std::move(*(sample_data_p.get())),
  312. std::move(hdl),
  313. std::ref(msg_data->msg),
  314. std::ref(*thread_lock_p),
  315. std::move(hotwords_embedding_),
  316. msg_data->msg["wav_name"],
  317. msg_data->msg["itn"],
  318. msg_data->msg["audio_fs"],
  319. msg_data->msg["wav_format"],
  320. std::ref(msg_data->decoder_handle)));
  321. msg_data->msg["access_num"]=(int)(msg_data->msg["access_num"])+1;
  322. }
  323. break;
  324. }
  325. case websocketpp::frame::opcode::binary: {
  326. // recived binary data
  327. const auto* pcm_data = static_cast<const char*>(payload.data());
  328. int32_t num_samples = payload.size();
  329. if (isonline) {
  330. // TODO
  331. } else {
  332. // for offline, we add receive data to end of the sample data vector
  333. sample_data_p->insert(sample_data_p->end(), pcm_data,
  334. pcm_data + num_samples);
  335. }
  336. break;
  337. }
  338. default:
  339. break;
  340. }
  341. }
  342. // init asr model
  343. void WebSocketServer::initAsr(std::map<std::string, std::string>& model_path,
  344. int thread_num) {
  345. try {
  346. // init model with api
  347. asr_handle = FunOfflineInit(model_path, thread_num);
  348. LOG(INFO) << "model successfully inited";
  349. LOG(INFO) << "initAsr run check_and_clean_connection";
  350. std::thread clean_thread(&WebSocketServer::check_and_clean_connection,this);
  351. clean_thread.detach();
  352. LOG(INFO) << "initAsr run check_and_clean_connection finished";
  353. } catch (const std::exception& e) {
  354. LOG(INFO) << e.what();
  355. }
  356. }