websocket-server.cpp 14 KB

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