websocket-server-2pass.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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-2pass.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. context_ptr WebSocketServer::on_tls_init(tls_mode mode,
  18. websocketpp::connection_hdl hdl,
  19. std::string& s_certfile,
  20. std::string& s_keyfile) {
  21. namespace asio = websocketpp::lib::asio;
  22. LOG(INFO) << "on_tls_init called with hdl: " << hdl.lock().get();
  23. LOG(INFO) << "using TLS mode: "
  24. << (mode == MOZILLA_MODERN ? "Mozilla Modern"
  25. : "Mozilla Intermediate");
  26. context_ptr ctx = websocketpp::lib::make_shared<asio::ssl::context>(
  27. asio::ssl::context::sslv23);
  28. try {
  29. if (mode == MOZILLA_MODERN) {
  30. // Modern disables TLSv1
  31. ctx->set_options(
  32. asio::ssl::context::default_workarounds |
  33. asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3 |
  34. asio::ssl::context::no_tlsv1 | asio::ssl::context::single_dh_use);
  35. } else {
  36. ctx->set_options(asio::ssl::context::default_workarounds |
  37. asio::ssl::context::no_sslv2 |
  38. asio::ssl::context::no_sslv3 |
  39. asio::ssl::context::single_dh_use);
  40. }
  41. ctx->use_certificate_chain_file(s_certfile);
  42. ctx->use_private_key_file(s_keyfile, asio::ssl::context::pem);
  43. } catch (std::exception& e) {
  44. LOG(INFO) << "Exception: " << e.what();
  45. }
  46. return ctx;
  47. }
  48. nlohmann::json handle_result(FUNASR_RESULT result) {
  49. websocketpp::lib::error_code ec;
  50. nlohmann::json jsonresult;
  51. jsonresult["text"] = "";
  52. std::string tmp_online_msg = FunASRGetResult(result, 0);
  53. if (tmp_online_msg != "") {
  54. LOG(INFO) << "online_res :" << tmp_online_msg;
  55. jsonresult["text"] = tmp_online_msg;
  56. jsonresult["mode"] = "2pass-online";
  57. }
  58. std::string tmp_tpass_msg = FunASRGetTpassResult(result, 0);
  59. if (tmp_tpass_msg != "") {
  60. LOG(INFO) << "offline results : " << tmp_tpass_msg;
  61. jsonresult["text"] = tmp_tpass_msg;
  62. jsonresult["mode"] = "2pass-offline";
  63. }
  64. std::string tmp_stamp_msg = FunASRGetStamp(result);
  65. if (tmp_stamp_msg != "") {
  66. LOG(INFO) << "offline stamps : " << tmp_stamp_msg;
  67. jsonresult["timestamp"] = tmp_stamp_msg;
  68. }
  69. return jsonresult;
  70. }
  71. // feed buffer to asr engine for decoder
  72. void WebSocketServer::do_decoder(
  73. std::vector<char>& buffer,
  74. websocketpp::connection_hdl& hdl,
  75. nlohmann::json& msg,
  76. std::vector<std::vector<std::string>>& punc_cache,
  77. std::vector<std::vector<float>> &hotwords_embedding,
  78. websocketpp::lib::mutex& thread_lock,
  79. bool& is_final,
  80. std::string wav_name,
  81. std::string modetype,
  82. bool itn,
  83. int audio_fs,
  84. std::string wav_format,
  85. FUNASR_HANDLE& tpass_online_handle) {
  86. // lock for each connection
  87. scoped_lock guard(thread_lock);
  88. if(!tpass_online_handle){
  89. LOG(INFO) << "tpass_online_handle is free, return";
  90. msg["access_num"]=(int)msg["access_num"]-1;
  91. return;
  92. }
  93. try {
  94. FUNASR_RESULT Result = nullptr;
  95. int asr_mode_ = 2;
  96. if (modetype == "offline") {
  97. asr_mode_ = 0;
  98. } else if (modetype == "online") {
  99. asr_mode_ = 1;
  100. } else if (modetype == "2pass") {
  101. asr_mode_ = 2;
  102. }
  103. while (buffer.size() >= 800 * 2 && !msg["is_eof"]) {
  104. std::vector<char> subvector = {buffer.begin(), buffer.begin() + 800 * 2};
  105. buffer.erase(buffer.begin(), buffer.begin() + 800 * 2);
  106. try {
  107. if (tpass_online_handle) {
  108. Result = FunTpassInferBuffer(tpass_handle, tpass_online_handle,
  109. subvector.data(), subvector.size(),
  110. punc_cache, false, audio_fs,
  111. wav_format, (ASR_TYPE)asr_mode_,
  112. hotwords_embedding, itn);
  113. } else {
  114. msg["access_num"]=(int)msg["access_num"]-1;
  115. return;
  116. }
  117. } catch (std::exception const& e) {
  118. LOG(ERROR) << e.what();
  119. msg["access_num"]=(int)msg["access_num"]-1;
  120. return;
  121. }
  122. if (Result) {
  123. websocketpp::lib::error_code ec;
  124. nlohmann::json jsonresult = handle_result(Result);
  125. jsonresult["wav_name"] = wav_name;
  126. jsonresult["is_final"] = false;
  127. if (jsonresult["text"] != "") {
  128. if (is_ssl) {
  129. wss_server_->send(hdl, jsonresult.dump(),
  130. websocketpp::frame::opcode::text, ec);
  131. } else {
  132. server_->send(hdl, jsonresult.dump(),
  133. websocketpp::frame::opcode::text, ec);
  134. }
  135. }
  136. FunASRFreeResult(Result);
  137. }
  138. }
  139. if (is_final && !msg["is_eof"]) {
  140. try {
  141. if (tpass_online_handle) {
  142. Result = FunTpassInferBuffer(tpass_handle, tpass_online_handle,
  143. buffer.data(), buffer.size(), punc_cache,
  144. is_final, audio_fs,
  145. wav_format, (ASR_TYPE)asr_mode_,
  146. hotwords_embedding, itn);
  147. } else {
  148. msg["access_num"]=(int)msg["access_num"]-1;
  149. return;
  150. }
  151. } catch (std::exception const& e) {
  152. LOG(ERROR) << e.what();
  153. msg["access_num"]=(int)msg["access_num"]-1;
  154. return;
  155. }
  156. if(punc_cache.size()>0){
  157. for (auto& vec : punc_cache) {
  158. vec.clear();
  159. }
  160. }
  161. if (Result) {
  162. websocketpp::lib::error_code ec;
  163. nlohmann::json jsonresult = handle_result(Result);
  164. jsonresult["wav_name"] = wav_name;
  165. jsonresult["is_final"] = true;
  166. if (is_ssl) {
  167. wss_server_->send(hdl, jsonresult.dump(),
  168. websocketpp::frame::opcode::text, ec);
  169. } else {
  170. server_->send(hdl, jsonresult.dump(),
  171. websocketpp::frame::opcode::text, ec);
  172. }
  173. FunASRFreeResult(Result);
  174. }else{
  175. if(wav_format != "pcm" && wav_format != "PCM"){
  176. websocketpp::lib::error_code ec;
  177. nlohmann::json jsonresult;
  178. jsonresult["text"] = "ERROR. Real-time transcription service ONLY SUPPORT wav_format pcm.";
  179. jsonresult["wav_name"] = wav_name;
  180. jsonresult["is_final"] = true;
  181. if (is_ssl) {
  182. wss_server_->send(hdl, jsonresult.dump(),
  183. websocketpp::frame::opcode::text, ec);
  184. } else {
  185. server_->send(hdl, jsonresult.dump(),
  186. websocketpp::frame::opcode::text, ec);
  187. }
  188. }
  189. }
  190. }
  191. } catch (std::exception const& e) {
  192. std::cerr << "Error: " << e.what() << std::endl;
  193. }
  194. msg["access_num"]=(int)msg["access_num"]-1;
  195. }
  196. void WebSocketServer::on_open(websocketpp::connection_hdl hdl) {
  197. scoped_lock guard(m_lock); // for threads safty
  198. try{
  199. std::shared_ptr<FUNASR_MESSAGE> data_msg =
  200. std::make_shared<FUNASR_MESSAGE>(); // put a new data vector for new
  201. // connection
  202. data_msg->samples = std::make_shared<std::vector<char>>();
  203. data_msg->thread_lock = std::make_shared<websocketpp::lib::mutex>();
  204. data_msg->msg = nlohmann::json::parse("{}");
  205. data_msg->msg["wav_format"] = "pcm";
  206. data_msg->msg["wav_name"] = "wav-default-id";
  207. data_msg->msg["mode"] = "2pass";
  208. data_msg->msg["itn"] = true;
  209. data_msg->msg["audio_fs"] = 16000;
  210. data_msg->msg["access_num"] = 0; // the number of access for this object, when it is 0, we can free it saftly
  211. data_msg->msg["is_eof"]=false; // if this connection is closed
  212. data_msg->punc_cache =
  213. std::make_shared<std::vector<std::vector<std::string>>>(2);
  214. data_msg->strand_ = std::make_shared<asio::io_context::strand>(io_decoder_);
  215. data_map.emplace(hdl, data_msg);
  216. }catch (std::exception const& e) {
  217. std::cerr << "Error: " << e.what() << std::endl;
  218. }
  219. }
  220. void remove_hdl(
  221. websocketpp::connection_hdl hdl,
  222. std::map<websocketpp::connection_hdl, std::shared_ptr<FUNASR_MESSAGE>,
  223. std::owner_less<websocketpp::connection_hdl>>& data_map) {
  224. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  225. auto it_data = data_map.find(hdl);
  226. if (it_data != data_map.end()) {
  227. data_msg = it_data->second;
  228. } else {
  229. return;
  230. }
  231. // scoped_lock guard_decoder(*(data_msg->thread_lock)); //wait for do_decoder
  232. // finished and avoid access freed tpass_online_handle
  233. unique_lock guard_decoder(*(data_msg->thread_lock));
  234. if (data_msg->msg["access_num"]==0 && data_msg->msg["is_eof"]==true) {
  235. FunTpassOnlineUninit(data_msg->tpass_online_handle);
  236. data_msg->tpass_online_handle = nullptr;
  237. data_map.erase(hdl);
  238. }
  239. guard_decoder.unlock();
  240. }
  241. void WebSocketServer::on_close(websocketpp::connection_hdl hdl) {
  242. scoped_lock guard(m_lock);
  243. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  244. auto it_data = data_map.find(hdl);
  245. if (it_data != data_map.end()) {
  246. data_msg = it_data->second;
  247. } else {
  248. return;
  249. }
  250. unique_lock guard_decoder(*(data_msg->thread_lock));
  251. data_msg->msg["is_eof"]=true;
  252. guard_decoder.unlock();
  253. }
  254. // remove closed connection
  255. void WebSocketServer::check_and_clean_connection() {
  256. while(true){
  257. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  258. std::vector<websocketpp::connection_hdl> to_remove; // remove list
  259. auto iter = data_map.begin();
  260. while (iter != data_map.end()) { // loop to find closed connection
  261. websocketpp::connection_hdl hdl = iter->first;
  262. try{
  263. if (is_ssl) {
  264. wss_server::connection_ptr con = wss_server_->get_con_from_hdl(hdl);
  265. if (con->get_state() != 1) { // session::state::open ==1
  266. to_remove.push_back(hdl);
  267. }
  268. } else {
  269. server::connection_ptr con = server_->get_con_from_hdl(hdl);
  270. if (con->get_state() != 1) { // session::state::open ==1
  271. to_remove.push_back(hdl);
  272. }
  273. }
  274. }
  275. catch (std::exception const &e)
  276. {
  277. // if connection is close, we set is_eof = true
  278. std::shared_ptr<FUNASR_MESSAGE> data_msg = nullptr;
  279. auto it_data = data_map.find(hdl);
  280. if (it_data != data_map.end()) {
  281. data_msg = it_data->second;
  282. } else {
  283. continue;
  284. }
  285. unique_lock guard_decoder(*(data_msg->thread_lock));
  286. data_msg->msg["is_eof"]=true;
  287. guard_decoder.unlock();
  288. to_remove.push_back(hdl);
  289. LOG(INFO)<<"connection is closed: "<<e.what();
  290. }
  291. iter++;
  292. }
  293. for (auto hdl : to_remove) {
  294. {
  295. unique_lock lock(m_lock);
  296. remove_hdl(hdl, data_map);
  297. }
  298. }
  299. }
  300. }
  301. void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
  302. message_ptr msg) {
  303. unique_lock lock(m_lock);
  304. // find the sample data vector according to one connection
  305. std::shared_ptr<FUNASR_MESSAGE> msg_data = nullptr;
  306. auto it_data = data_map.find(hdl);
  307. if (it_data != data_map.end()) {
  308. msg_data = it_data->second;
  309. } else {
  310. lock.unlock();
  311. return;
  312. }
  313. std::shared_ptr<std::vector<char>> sample_data_p = msg_data->samples;
  314. std::shared_ptr<std::vector<std::vector<std::string>>> punc_cache_p =
  315. msg_data->punc_cache;
  316. std::shared_ptr<websocketpp::lib::mutex> thread_lock_p = msg_data->thread_lock;
  317. lock.unlock();
  318. if (sample_data_p == nullptr) {
  319. LOG(INFO) << "error when fetch sample data vector";
  320. return;
  321. }
  322. const std::string& payload = msg->get_payload(); // get msg type
  323. unique_lock guard_decoder(*(thread_lock_p)); // mutex for one connection
  324. switch (msg->get_opcode()) {
  325. case websocketpp::frame::opcode::text: {
  326. nlohmann::json jsonresult;
  327. try{
  328. jsonresult = nlohmann::json::parse(payload);
  329. }catch (std::exception const &e)
  330. {
  331. LOG(ERROR)<<e.what();
  332. break;
  333. }
  334. if (jsonresult.contains("wav_name")) {
  335. msg_data->msg["wav_name"] = jsonresult["wav_name"];
  336. }
  337. if (jsonresult.contains("mode")) {
  338. msg_data->msg["mode"] = jsonresult["mode"];
  339. }
  340. if (jsonresult.contains("wav_format")) {
  341. msg_data->msg["wav_format"] = jsonresult["wav_format"];
  342. }
  343. // hotwords: fst/nn
  344. if(msg_data->hotwords_embedding == NULL){
  345. std::unordered_map<std::string, int> merged_hws_map;
  346. std::string nn_hotwords = "";
  347. if (jsonresult["hotwords"] != nullptr) {
  348. std::string json_string = jsonresult["hotwords"];
  349. if (!json_string.empty()){
  350. nlohmann::json json_fst_hws;
  351. try{
  352. json_fst_hws = nlohmann::json::parse(json_string);
  353. } catch (std::exception const &e)
  354. {
  355. LOG(ERROR)<<e.what();
  356. break;
  357. }
  358. if(json_fst_hws.type() == nlohmann::json::value_t::object){
  359. // fst
  360. try{
  361. std::unordered_map<std::string, int> client_hws_map = json_fst_hws;
  362. merged_hws_map.insert(client_hws_map.begin(), client_hws_map.end());
  363. } catch (const std::exception& e) {
  364. LOG(INFO) << e.what();
  365. }
  366. }else{
  367. // nn
  368. std::string client_nn_hws = jsonresult["hotwords"];
  369. nn_hotwords += " " + client_nn_hws;
  370. LOG(INFO) << "nn hotwords: " << client_nn_hws;
  371. }
  372. }
  373. }
  374. merged_hws_map.insert(hws_map_.begin(), hws_map_.end());
  375. // fst
  376. LOG(INFO) << "hotwords: ";
  377. for (const auto& pair : merged_hws_map) {
  378. nn_hotwords += " " + pair.first;
  379. LOG(INFO) << pair.first << " : " << pair.second;
  380. }
  381. // FunWfstDecoderLoadHwsRes(msg_data->decoder_handle, fst_inc_wts_, merged_hws_map);
  382. // nn
  383. std::vector<std::vector<float>> new_hotwords_embedding = CompileHotwordEmbedding(tpass_handle, nn_hotwords, ASR_TWO_PASS);
  384. msg_data->hotwords_embedding =
  385. std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
  386. }
  387. if (jsonresult.contains("audio_fs")) {
  388. msg_data->msg["audio_fs"] = jsonresult["audio_fs"];
  389. }
  390. if (jsonresult.contains("chunk_size")) {
  391. if (msg_data->tpass_online_handle == NULL) {
  392. std::vector<int> chunk_size_vec =
  393. jsonresult["chunk_size"].get<std::vector<int>>();
  394. // check chunk_size_vec
  395. if(chunk_size_vec.size() == 3 && chunk_size_vec[1] != 0){
  396. FUNASR_HANDLE tpass_online_handle =
  397. FunTpassOnlineInit(tpass_handle, chunk_size_vec);
  398. msg_data->tpass_online_handle = tpass_online_handle;
  399. }else{
  400. LOG(ERROR) << "Wrong chunk_size!";
  401. break;
  402. }
  403. }
  404. }
  405. if (jsonresult.contains("itn")) {
  406. msg_data->msg["itn"] = jsonresult["itn"];
  407. }
  408. LOG(INFO) << "jsonresult=" << jsonresult
  409. << ", msg_data->msg=" << msg_data->msg;
  410. if (jsonresult["is_speaking"] == false ||
  411. jsonresult["is_finished"] == true) {
  412. LOG(INFO) << "client done";
  413. // if it is in final message, post the sample_data to decode
  414. try{
  415. std::vector<std::vector<float>> hotwords_embedding_(*(msg_data->hotwords_embedding));
  416. msg_data->strand_->post(
  417. std::bind(&WebSocketServer::do_decoder, this,
  418. std::move(*(sample_data_p.get())), std::move(hdl),
  419. std::ref(msg_data->msg), std::ref(*(punc_cache_p.get())),
  420. std::move(hotwords_embedding_),
  421. std::ref(*thread_lock_p), std::move(true),
  422. msg_data->msg["wav_name"],
  423. msg_data->msg["mode"],
  424. msg_data->msg["itn"],
  425. msg_data->msg["audio_fs"],
  426. msg_data->msg["wav_format"],
  427. std::ref(msg_data->tpass_online_handle)));
  428. msg_data->msg["access_num"]=(int)(msg_data->msg["access_num"])+1;
  429. }
  430. catch (std::exception const &e)
  431. {
  432. LOG(ERROR)<<e.what();
  433. }
  434. }
  435. break;
  436. }
  437. case websocketpp::frame::opcode::binary: {
  438. // recived binary data
  439. const auto* pcm_data = static_cast<const char*>(payload.data());
  440. int32_t num_samples = payload.size();
  441. if (isonline) {
  442. sample_data_p->insert(sample_data_p->end(), pcm_data,
  443. pcm_data + num_samples);
  444. int setpsize =
  445. 800 * 2; // TODO, need get from client
  446. // if sample_data size > setpsize, we post data to decode
  447. if (sample_data_p->size() > setpsize) {
  448. int chunksize = floor(sample_data_p->size() / setpsize);
  449. // make sure the subvector size is an integer multiple of setpsize
  450. std::vector<char> subvector = {
  451. sample_data_p->begin(),
  452. sample_data_p->begin() + chunksize * setpsize};
  453. // keep remain in sample_data
  454. sample_data_p->erase(sample_data_p->begin(),
  455. sample_data_p->begin() + chunksize * setpsize);
  456. try{
  457. // post to decode
  458. std::vector<std::vector<float>> hotwords_embedding_(*(msg_data->hotwords_embedding));
  459. msg_data->strand_->post(
  460. std::bind(&WebSocketServer::do_decoder, this,
  461. std::move(subvector), std::move(hdl),
  462. std::ref(msg_data->msg),
  463. std::ref(*(punc_cache_p.get())),
  464. std::move(hotwords_embedding_),
  465. std::ref(*thread_lock_p), std::move(false),
  466. msg_data->msg["wav_name"],
  467. msg_data->msg["mode"],
  468. msg_data->msg["itn"],
  469. msg_data->msg["audio_fs"],
  470. msg_data->msg["wav_format"],
  471. std::ref(msg_data->tpass_online_handle)));
  472. msg_data->msg["access_num"]=(int)(msg_data->msg["access_num"])+1;
  473. }
  474. catch (std::exception const &e)
  475. {
  476. LOG(ERROR)<<e.what();
  477. }
  478. }
  479. } else {
  480. sample_data_p->insert(sample_data_p->end(), pcm_data,
  481. pcm_data + num_samples);
  482. }
  483. break;
  484. }
  485. default:
  486. break;
  487. }
  488. guard_decoder.unlock();
  489. }
  490. // init asr model
  491. void WebSocketServer::initAsr(std::map<std::string, std::string>& model_path,
  492. int thread_num) {
  493. try {
  494. tpass_handle = FunTpassInit(model_path, thread_num);
  495. if (!tpass_handle) {
  496. LOG(ERROR) << "FunTpassInit init failed";
  497. exit(-1);
  498. }
  499. LOG(INFO) << "initAsr run check_and_clean_connection";
  500. std::thread clean_thread(&WebSocketServer::check_and_clean_connection,this);
  501. clean_thread.detach();
  502. LOG(INFO) << "initAsr run check_and_clean_connection finished";
  503. } catch (const std::exception& e) {
  504. LOG(INFO) << e.what();
  505. }
  506. }