websocket-server.cpp 14 KB

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