funasr-wss-client.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. // client for websocket, support multiple threads
  7. // ./funasr-wss-client --server-ip <string>
  8. // --port <string>
  9. // --wav-path <string>
  10. // [--thread-num <int>]
  11. // [--is-ssl <int>] [--]
  12. // [--version] [-h]
  13. // example:
  14. // ./funasr-wss-client --server-ip 127.0.0.1 --port 10095 --wav-path test.wav --thread-num 1 --is-ssl 1
  15. #define ASIO_STANDALONE 1
  16. #include <websocketpp/client.hpp>
  17. #include <websocketpp/common/thread.hpp>
  18. #include <websocketpp/config/asio_client.hpp>
  19. #include <fstream>
  20. #include <atomic>
  21. #include <thread>
  22. #include <glog/logging.h>
  23. #include "util.h"
  24. #include "audio.h"
  25. #include "nlohmann/json.hpp"
  26. #include "tclap/CmdLine.h"
  27. /**
  28. * Define a semi-cross platform helper method that waits/sleeps for a bit.
  29. */
  30. void WaitABit() {
  31. #ifdef WIN32
  32. Sleep(200);
  33. #else
  34. usleep(200);
  35. #endif
  36. }
  37. std::atomic<int> wav_index(0);
  38. typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
  39. typedef websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context> context_ptr;
  40. using websocketpp::lib::bind;
  41. using websocketpp::lib::placeholders::_1;
  42. using websocketpp::lib::placeholders::_2;
  43. context_ptr OnTlsInit(websocketpp::connection_hdl) {
  44. context_ptr ctx = websocketpp::lib::make_shared<asio::ssl::context>(
  45. asio::ssl::context::sslv23);
  46. try {
  47. ctx->set_options(
  48. asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 |
  49. asio::ssl::context::no_sslv3 | asio::ssl::context::single_dh_use);
  50. } catch (std::exception& e) {
  51. LOG(ERROR) << e.what();
  52. }
  53. return ctx;
  54. }
  55. // template for tls or not config
  56. template <typename T>
  57. class WebsocketClient {
  58. public:
  59. // typedef websocketpp::client<T> client;
  60. // typedef websocketpp::client<websocketpp::config::asio_tls_client>
  61. // wss_client;
  62. typedef websocketpp::lib::lock_guard<websocketpp::lib::mutex> scoped_lock;
  63. WebsocketClient(int is_ssl) : m_open(false), m_done(false) {
  64. // set up access channels to only log interesting things
  65. m_client.clear_access_channels(websocketpp::log::alevel::all);
  66. m_client.set_access_channels(websocketpp::log::alevel::connect);
  67. m_client.set_access_channels(websocketpp::log::alevel::disconnect);
  68. m_client.set_access_channels(websocketpp::log::alevel::app);
  69. // Initialize the Asio transport policy
  70. m_client.init_asio();
  71. // Bind the handlers we are using
  72. using websocketpp::lib::bind;
  73. using websocketpp::lib::placeholders::_1;
  74. m_client.set_open_handler(bind(&WebsocketClient::on_open, this, _1));
  75. m_client.set_close_handler(bind(&WebsocketClient::on_close, this, _1));
  76. m_client.set_message_handler(
  77. [this](websocketpp::connection_hdl hdl, message_ptr msg) {
  78. on_message(hdl, msg);
  79. });
  80. m_client.set_fail_handler(bind(&WebsocketClient::on_fail, this, _1));
  81. m_client.clear_access_channels(websocketpp::log::alevel::all);
  82. }
  83. void on_message(websocketpp::connection_hdl hdl, message_ptr msg) {
  84. const std::string& payload = msg->get_payload();
  85. switch (msg->get_opcode()) {
  86. case websocketpp::frame::opcode::text:
  87. total_recv=total_recv+1;
  88. LOG(INFO)<< "Thread: " << this_thread::get_id() <<", on_message = " << payload;
  89. LOG(INFO)<< "Thread: " << this_thread::get_id() << ", total_recv=" << total_recv << " total_send=" <<total_send;
  90. if(total_recv==total_send)
  91. {
  92. LOG(INFO)<< "Thread: " << this_thread::get_id() << ", close client";
  93. websocketpp::lib::error_code ec;
  94. m_client.close(m_hdl, websocketpp::close::status::going_away, "", ec);
  95. if (ec){
  96. LOG(ERROR)<< "Error closing connection " << ec.message();
  97. }
  98. }
  99. }
  100. }
  101. // This method will block until the connection is complete
  102. void run(const std::string& uri, const std::vector<string>& wav_list, const std::vector<string>& wav_ids,
  103. int audio_fs, const std::unordered_map<std::string, int>& hws_map, int use_itn=1) {
  104. // Create a new connection to the given URI
  105. websocketpp::lib::error_code ec;
  106. typename websocketpp::client<T>::connection_ptr con =
  107. m_client.get_connection(uri, ec);
  108. if (ec) {
  109. m_client.get_alog().write(websocketpp::log::alevel::app,
  110. "Get Connection Error: " + ec.message());
  111. return;
  112. }
  113. // Grab a handle for this connection so we can talk to it in a thread
  114. // safe manor after the event loop starts.
  115. m_hdl = con->get_handle();
  116. // Queue the connection. No DNS queries or network connections will be
  117. // made until the io_service event loop is run.
  118. m_client.connect(con);
  119. // Create a thread to run the ASIO io_service event loop
  120. websocketpp::lib::thread asio_thread(&websocketpp::client<T>::run,
  121. &m_client);
  122. bool send_hotword = true;
  123. while(true){
  124. int i = wav_index.fetch_add(1);
  125. if (i >= wav_list.size()) {
  126. break;
  127. }
  128. total_send += 1;
  129. send_wav_data(wav_list[i], wav_ids[i], audio_fs, hws_map, send_hotword, use_itn);
  130. if(send_hotword){
  131. send_hotword = false;
  132. }
  133. }
  134. WaitABit();
  135. asio_thread.join();
  136. }
  137. // The open handler will signal that we are ready to start sending data
  138. void on_open(websocketpp::connection_hdl) {
  139. m_client.get_alog().write(websocketpp::log::alevel::app,
  140. "Connection opened, starting data!");
  141. scoped_lock guard(m_lock);
  142. m_open = true;
  143. }
  144. // The close handler will signal that we should stop sending data
  145. void on_close(websocketpp::connection_hdl) {
  146. m_client.get_alog().write(websocketpp::log::alevel::app,
  147. "Connection closed, stopping data!");
  148. scoped_lock guard(m_lock);
  149. m_done = true;
  150. }
  151. // The fail handler will signal that we should stop sending data
  152. void on_fail(websocketpp::connection_hdl) {
  153. m_client.get_alog().write(websocketpp::log::alevel::app,
  154. "Connection failed, stopping data!");
  155. scoped_lock guard(m_lock);
  156. m_done = true;
  157. }
  158. // send wav to server
  159. void send_wav_data(string wav_path, string wav_id, int audio_fs,
  160. const std::unordered_map<std::string, int>& hws_map,
  161. bool send_hotword, bool use_itn) {
  162. uint64_t count = 0;
  163. std::stringstream val;
  164. funasr::Audio audio(1);
  165. int32_t sampling_rate = audio_fs;
  166. std::string wav_format = "pcm";
  167. if(funasr::IsTargetFile(wav_path.c_str(), "pcm")){
  168. if (!audio.LoadPcmwav(wav_path.c_str(), &sampling_rate, false))
  169. return ;
  170. }else{
  171. wav_format = "others";
  172. if (!audio.LoadOthers2Char(wav_path.c_str()))
  173. return ;
  174. }
  175. float* buff;
  176. int len;
  177. int flag = 0;
  178. bool wait = false;
  179. while (1) {
  180. {
  181. scoped_lock guard(m_lock);
  182. // If the connection has been closed, stop generating data
  183. if (m_done) {
  184. break;
  185. }
  186. // If the connection hasn't been opened yet wait a bit and retry
  187. if (!m_open) {
  188. wait = true;
  189. } else {
  190. break;
  191. }
  192. }
  193. if (wait) {
  194. // LOG(INFO) << "wait.." << m_open;
  195. WaitABit();
  196. continue;
  197. }
  198. }
  199. websocketpp::lib::error_code ec;
  200. nlohmann::json jsonbegin;
  201. nlohmann::json chunk_size = nlohmann::json::array();
  202. chunk_size.push_back(5);
  203. chunk_size.push_back(10);
  204. chunk_size.push_back(5);
  205. jsonbegin["chunk_size"] = chunk_size;
  206. jsonbegin["chunk_interval"] = 10;
  207. jsonbegin["wav_name"] = wav_id;
  208. jsonbegin["wav_format"] = wav_format;
  209. jsonbegin["audio_fs"] = sampling_rate;
  210. jsonbegin["itn"] = true;
  211. if(use_itn == 0){
  212. jsonbegin["itn"] = false;
  213. }
  214. jsonbegin["is_speaking"] = true;
  215. if(send_hotword){
  216. if(!hws_map.empty()){
  217. LOG(INFO) << "hotwords: ";
  218. for (const auto& pair : hws_map) {
  219. LOG(INFO) << pair.first << " : " << pair.second;
  220. }
  221. nlohmann::json json_map(hws_map);
  222. std::string json_map_str = json_map.dump();
  223. jsonbegin["hotwords"] = json_map_str;
  224. }
  225. }
  226. m_client.send(m_hdl, jsonbegin.dump(), websocketpp::frame::opcode::text,
  227. ec);
  228. // fetch wav data use asr engine api
  229. if(wav_format == "pcm"){
  230. while (audio.Fetch(buff, len, flag) > 0) {
  231. short* iArray = new short[len];
  232. for (size_t i = 0; i < len; ++i) {
  233. iArray[i] = (short)(buff[i]*32768);
  234. }
  235. // send data to server
  236. int offset = 0;
  237. int block_size = 102400;
  238. while(offset < len){
  239. int send_block = 0;
  240. if (offset + block_size <= len){
  241. send_block = block_size;
  242. }else{
  243. send_block = len - offset;
  244. }
  245. m_client.send(m_hdl, iArray+offset, send_block * sizeof(short),
  246. websocketpp::frame::opcode::binary, ec);
  247. offset += send_block;
  248. }
  249. LOG(INFO)<< "Thread: " << this_thread::get_id() << ", sended data len=" << len * sizeof(short);
  250. // The most likely error that we will get is that the connection is
  251. // not in the right state. Usually this means we tried to send a
  252. // message to a connection that was closed or in the process of
  253. // closing. While many errors here can be easily recovered from,
  254. // in this simple example, we'll stop the data loop.
  255. if (ec) {
  256. m_client.get_alog().write(websocketpp::log::alevel::app,
  257. "Send Error: " + ec.message());
  258. break;
  259. }
  260. delete[] iArray;
  261. // WaitABit();
  262. }
  263. }else{
  264. int offset = 0;
  265. int block_size = 204800;
  266. len = audio.GetSpeechLen();
  267. char* others_buff = audio.GetSpeechChar();
  268. while(offset < len){
  269. int send_block = 0;
  270. if (offset + block_size <= len){
  271. send_block = block_size;
  272. }else{
  273. send_block = len - offset;
  274. }
  275. m_client.send(m_hdl, others_buff+offset, send_block,
  276. websocketpp::frame::opcode::binary, ec);
  277. offset += send_block;
  278. }
  279. LOG(INFO)<< "Thread: " << this_thread::get_id() << ", sended data len=" << len;
  280. // The most likely error that we will get is that the connection is
  281. // not in the right state. Usually this means we tried to send a
  282. // message to a connection that was closed or in the process of
  283. // closing. While many errors here can be easily recovered from,
  284. // in this simple example, we'll stop the data loop.
  285. if (ec) {
  286. m_client.get_alog().write(websocketpp::log::alevel::app,
  287. "Send Error: " + ec.message());
  288. }
  289. }
  290. nlohmann::json jsonresult;
  291. jsonresult["is_speaking"] = false;
  292. m_client.send(m_hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  293. ec);
  294. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  295. }
  296. websocketpp::client<T> m_client;
  297. private:
  298. websocketpp::connection_hdl m_hdl;
  299. websocketpp::lib::mutex m_lock;
  300. bool m_open;
  301. bool m_done;
  302. int total_send=0;
  303. int total_recv=0;
  304. };
  305. int main(int argc, char* argv[]) {
  306. #ifdef _WIN32
  307. #include <windows.h>
  308. SetConsoleOutputCP(65001);
  309. #endif
  310. google::InitGoogleLogging(argv[0]);
  311. FLAGS_logtostderr = true;
  312. TCLAP::CmdLine cmd("funasr-wss-client", ' ', "1.0");
  313. TCLAP::ValueArg<std::string> server_ip_("", "server-ip", "server-ip", true,
  314. "127.0.0.1", "string");
  315. TCLAP::ValueArg<std::string> port_("", "port", "port", true, "10095", "string");
  316. TCLAP::ValueArg<std::string> wav_path_("", "wav-path",
  317. "the input could be: wav_path, e.g.: asr_example.wav; pcm_path, e.g.: asr_example.pcm; wav.scp, kaldi style wav list (wav_id \t wav_path)",
  318. true, "", "string");
  319. TCLAP::ValueArg<std::int32_t> audio_fs_("", "audio-fs", "the sample rate of audio", false, 16000, "int32_t");
  320. TCLAP::ValueArg<int> thread_num_("", "thread-num", "thread-num",
  321. false, 1, "int");
  322. TCLAP::ValueArg<int> is_ssl_(
  323. "", "is-ssl", "is-ssl is 1 means use wss connection, or use ws connection",
  324. false, 1, "int");
  325. TCLAP::ValueArg<int> use_itn_(
  326. "", "use-itn",
  327. "use-itn is 1 means use itn, 0 means not use itn", false, 1, "int");
  328. TCLAP::ValueArg<std::string> hotword_("", HOTWORD,
  329. "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
  330. cmd.add(server_ip_);
  331. cmd.add(port_);
  332. cmd.add(wav_path_);
  333. cmd.add(audio_fs_);
  334. cmd.add(thread_num_);
  335. cmd.add(is_ssl_);
  336. cmd.add(use_itn_);
  337. cmd.add(hotword_);
  338. cmd.parse(argc, argv);
  339. std::string server_ip = server_ip_.getValue();
  340. std::string port = port_.getValue();
  341. std::string wav_path = wav_path_.getValue();
  342. int threads_num = thread_num_.getValue();
  343. int is_ssl = is_ssl_.getValue();
  344. int use_itn = use_itn_.getValue();
  345. std::vector<websocketpp::lib::thread> client_threads;
  346. std::string uri = "";
  347. if (is_ssl == 1) {
  348. uri = "wss://" + server_ip + ":" + port;
  349. } else {
  350. uri = "ws://" + server_ip + ":" + port;
  351. }
  352. // hotwords
  353. std::string hotword_path = hotword_.getValue();
  354. unordered_map<string, int> hws_map;
  355. if(!hotword_path.empty()){
  356. LOG(INFO) << "hotword path: " << hotword_path;
  357. funasr::ExtractHws(hotword_path, hws_map);
  358. }
  359. // read wav_path
  360. std::vector<string> wav_list;
  361. std::vector<string> wav_ids;
  362. string default_id = "wav_default_id";
  363. if(funasr::IsTargetFile(wav_path, "scp")){
  364. ifstream in(wav_path);
  365. if (!in.is_open()) {
  366. printf("Failed to open scp file");
  367. return 0;
  368. }
  369. string line;
  370. while(getline(in, line))
  371. {
  372. istringstream iss(line);
  373. string column1, column2;
  374. iss >> column1 >> column2;
  375. wav_list.emplace_back(column2);
  376. wav_ids.emplace_back(column1);
  377. }
  378. in.close();
  379. }else{
  380. wav_list.emplace_back(wav_path);
  381. wav_ids.emplace_back(default_id);
  382. }
  383. int audio_fs = audio_fs_.getValue();
  384. for (size_t i = 0; i < threads_num; i++) {
  385. client_threads.emplace_back([uri, wav_list, wav_ids, audio_fs, is_ssl, hws_map, use_itn]() {
  386. if (is_ssl == 1) {
  387. WebsocketClient<websocketpp::config::asio_tls_client> c(is_ssl);
  388. c.m_client.set_tls_init_handler(bind(&OnTlsInit, ::_1));
  389. c.run(uri, wav_list, wav_ids, audio_fs, hws_map, use_itn);
  390. } else {
  391. WebsocketClient<websocketpp::config::asio_client> c(is_ssl);
  392. c.run(uri, wav_list, wav_ids, audio_fs, hws_map, use_itn);
  393. }
  394. });
  395. }
  396. for (auto& t : client_threads) {
  397. t.join();
  398. }
  399. }