websocket-server.cpp 15 KB

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