funasr-wss-client.cpp 16 KB

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