funasr-wss-client.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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_num=total_num+1;
  95. LOG(INFO)<< "Thread: " << this_thread::get_id() <<",on_message = " << payload;
  96. LOG(INFO) << "total_num=" << total_num << " wav_index=" <<wav_index;
  97. if((total_num+1)==wav_index)
  98. {
  99. LOG(INFO) << "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, std::string hotwords) {
  110. // Create a new connection to the given URI
  111. websocketpp::lib::error_code ec;
  112. typename websocketpp::client<T>::connection_ptr con =
  113. m_client.get_connection(uri, ec);
  114. if (ec) {
  115. m_client.get_alog().write(websocketpp::log::alevel::app,
  116. "Get Connection Error: " + ec.message());
  117. return;
  118. }
  119. // Grab a handle for this connection so we can talk to it in a thread
  120. // safe manor after the event loop starts.
  121. m_hdl = con->get_handle();
  122. // Queue the connection. No DNS queries or network connections will be
  123. // made until the io_service event loop is run.
  124. m_client.connect(con);
  125. // Create a thread to run the ASIO io_service event loop
  126. websocketpp::lib::thread asio_thread(&websocketpp::client<T>::run,
  127. &m_client);
  128. bool send_hotword = true;
  129. while(true){
  130. int i = wav_index.fetch_add(1);
  131. if (i >= wav_list.size()) {
  132. break;
  133. }
  134. send_wav_data(wav_list[i], wav_ids[i], hotwords, send_hotword);
  135. if(send_hotword){
  136. send_hotword = false;
  137. }
  138. }
  139. WaitABit();
  140. asio_thread.join();
  141. }
  142. // The open handler will signal that we are ready to start sending data
  143. void on_open(websocketpp::connection_hdl) {
  144. m_client.get_alog().write(websocketpp::log::alevel::app,
  145. "Connection opened, starting data!");
  146. scoped_lock guard(m_lock);
  147. m_open = true;
  148. }
  149. // The close handler will signal that we should stop sending data
  150. void on_close(websocketpp::connection_hdl) {
  151. m_client.get_alog().write(websocketpp::log::alevel::app,
  152. "Connection closed, stopping data!");
  153. scoped_lock guard(m_lock);
  154. m_done = true;
  155. }
  156. // The fail handler will signal that we should stop sending data
  157. void on_fail(websocketpp::connection_hdl) {
  158. m_client.get_alog().write(websocketpp::log::alevel::app,
  159. "Connection failed, stopping data!");
  160. scoped_lock guard(m_lock);
  161. m_done = true;
  162. }
  163. // send wav to server
  164. void send_wav_data(string wav_path, string wav_id, string hotwords, bool send_hotword) {
  165. uint64_t count = 0;
  166. std::stringstream val;
  167. funasr::Audio audio(1);
  168. int32_t sampling_rate = 16000;
  169. std::string wav_format = "pcm";
  170. if(IsTargetFile(wav_path.c_str(), "wav")){
  171. int32_t sampling_rate = -1;
  172. if(!audio.LoadWav(wav_path.c_str(), &sampling_rate))
  173. return ;
  174. }else if(IsTargetFile(wav_path.c_str(), "pcm")){
  175. if (!audio.LoadPcmwav(wav_path.c_str(), &sampling_rate))
  176. return ;
  177. }else{
  178. wav_format = "others";
  179. if (!audio.LoadOthers2Char(wav_path.c_str()))
  180. return ;
  181. }
  182. float* buff;
  183. int len;
  184. int flag = 0;
  185. bool wait = false;
  186. while (1) {
  187. {
  188. scoped_lock guard(m_lock);
  189. // If the connection has been closed, stop generating data
  190. if (m_done) {
  191. break;
  192. }
  193. // If the connection hasn't been opened yet wait a bit and retry
  194. if (!m_open) {
  195. wait = true;
  196. } else {
  197. break;
  198. }
  199. }
  200. if (wait) {
  201. // LOG(INFO) << "wait.." << m_open;
  202. WaitABit();
  203. continue;
  204. }
  205. }
  206. websocketpp::lib::error_code ec;
  207. nlohmann::json jsonbegin;
  208. nlohmann::json chunk_size = nlohmann::json::array();
  209. chunk_size.push_back(5);
  210. chunk_size.push_back(0);
  211. chunk_size.push_back(5);
  212. jsonbegin["chunk_size"] = chunk_size;
  213. jsonbegin["chunk_interval"] = 10;
  214. jsonbegin["wav_name"] = wav_id;
  215. jsonbegin["wav_format"] = wav_format;
  216. jsonbegin["is_speaking"] = true;
  217. if(send_hotword){
  218. LOG(INFO) << "hotwords: "<< hotwords;
  219. jsonbegin["hotwords"] = hotwords;
  220. }
  221. m_client.send(m_hdl, jsonbegin.dump(), websocketpp::frame::opcode::text,
  222. ec);
  223. // fetch wav data use asr engine api
  224. if(wav_format == "pcm"){
  225. while (audio.Fetch(buff, len, flag) > 0) {
  226. short* iArray = new short[len];
  227. for (size_t i = 0; i < len; ++i) {
  228. iArray[i] = (short)(buff[i]*32768);
  229. }
  230. // send data to server
  231. int offset = 0;
  232. int block_size = 102400;
  233. while(offset < len){
  234. int send_block = 0;
  235. if (offset + block_size <= len){
  236. send_block = block_size;
  237. }else{
  238. send_block = len - offset;
  239. }
  240. m_client.send(m_hdl, iArray+offset, send_block * sizeof(short),
  241. websocketpp::frame::opcode::binary, ec);
  242. offset += send_block;
  243. }
  244. LOG(INFO) << "sended data len=" << len * sizeof(short);
  245. // The most likely error that we will get is that the connection is
  246. // not in the right state. Usually this means we tried to send a
  247. // message to a connection that was closed or in the process of
  248. // closing. While many errors here can be easily recovered from,
  249. // in this simple example, we'll stop the data loop.
  250. if (ec) {
  251. m_client.get_alog().write(websocketpp::log::alevel::app,
  252. "Send Error: " + ec.message());
  253. break;
  254. }
  255. delete[] iArray;
  256. // WaitABit();
  257. }
  258. }else{
  259. int offset = 0;
  260. int block_size = 204800;
  261. len = audio.GetSpeechLen();
  262. char* others_buff = audio.GetSpeechChar();
  263. while(offset < len){
  264. int send_block = 0;
  265. if (offset + block_size <= len){
  266. send_block = block_size;
  267. }else{
  268. send_block = len - offset;
  269. }
  270. m_client.send(m_hdl, others_buff+offset, send_block,
  271. websocketpp::frame::opcode::binary, ec);
  272. offset += send_block;
  273. }
  274. LOG(INFO) << "sended data len=" << len;
  275. // The most likely error that we will get is that the connection is
  276. // not in the right state. Usually this means we tried to send a
  277. // message to a connection that was closed or in the process of
  278. // closing. While many errors here can be easily recovered from,
  279. // in this simple example, we'll stop the data loop.
  280. if (ec) {
  281. m_client.get_alog().write(websocketpp::log::alevel::app,
  282. "Send Error: " + ec.message());
  283. }
  284. }
  285. nlohmann::json jsonresult;
  286. jsonresult["is_speaking"] = false;
  287. m_client.send(m_hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  288. ec);
  289. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  290. }
  291. websocketpp::client<T> m_client;
  292. private:
  293. websocketpp::connection_hdl m_hdl;
  294. websocketpp::lib::mutex m_lock;
  295. bool m_open;
  296. bool m_done;
  297. int total_num=0;
  298. };
  299. int main(int argc, char* argv[]) {
  300. google::InitGoogleLogging(argv[0]);
  301. FLAGS_logtostderr = true;
  302. TCLAP::CmdLine cmd("funasr-wss-client", ' ', "1.0");
  303. TCLAP::ValueArg<std::string> server_ip_("", "server-ip", "server-ip", true,
  304. "127.0.0.1", "string");
  305. TCLAP::ValueArg<std::string> port_("", "port", "port", true, "10095", "string");
  306. TCLAP::ValueArg<std::string> wav_path_("", "wav-path",
  307. "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)",
  308. true, "", "string");
  309. TCLAP::ValueArg<int> thread_num_("", "thread-num", "thread-num",
  310. false, 1, "int");
  311. TCLAP::ValueArg<int> is_ssl_(
  312. "", "is-ssl", "is-ssl is 1 means use wss connection, or use ws connection",
  313. false, 1, "int");
  314. TCLAP::ValueArg<std::string> hotword_("", HOTWORD, "*.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)", false, "", "string");
  315. cmd.add(server_ip_);
  316. cmd.add(port_);
  317. cmd.add(wav_path_);
  318. cmd.add(thread_num_);
  319. cmd.add(is_ssl_);
  320. cmd.add(hotword_);
  321. cmd.parse(argc, argv);
  322. std::string server_ip = server_ip_.getValue();
  323. std::string port = port_.getValue();
  324. std::string wav_path = wav_path_.getValue();
  325. int threads_num = thread_num_.getValue();
  326. int is_ssl = is_ssl_.getValue();
  327. std::vector<websocketpp::lib::thread> client_threads;
  328. std::string uri = "";
  329. if (is_ssl == 1) {
  330. uri = "wss://" + server_ip + ":" + port;
  331. } else {
  332. uri = "ws://" + server_ip + ":" + port;
  333. }
  334. // read hotwords
  335. std::string hotword = hotword_.getValue();
  336. std::string hotwords_;
  337. if(IsTargetFile(hotword, "txt")){
  338. ifstream in(hotword);
  339. if (!in.is_open()) {
  340. LOG(ERROR) << "Failed to open file: " << hotword;
  341. return 0;
  342. }
  343. string line;
  344. while(getline(in, line))
  345. {
  346. hotwords_ +=line+HOTWORD_SEP;
  347. }
  348. in.close();
  349. }else{
  350. hotwords_ = hotword;
  351. }
  352. // read wav_path
  353. std::vector<string> wav_list;
  354. std::vector<string> wav_ids;
  355. string default_id = "wav_default_id";
  356. if(IsTargetFile(wav_path, "scp")){
  357. ifstream in(wav_path);
  358. if (!in.is_open()) {
  359. printf("Failed to open scp file");
  360. return 0;
  361. }
  362. string line;
  363. while(getline(in, line))
  364. {
  365. istringstream iss(line);
  366. string column1, column2;
  367. iss >> column1 >> column2;
  368. wav_list.emplace_back(column2);
  369. wav_ids.emplace_back(column1);
  370. }
  371. in.close();
  372. }else{
  373. wav_list.emplace_back(wav_path);
  374. wav_ids.emplace_back(default_id);
  375. }
  376. for (size_t i = 0; i < threads_num; i++) {
  377. client_threads.emplace_back([uri, wav_list, wav_ids, is_ssl, hotwords_]() {
  378. if (is_ssl == 1) {
  379. WebsocketClient<websocketpp::config::asio_tls_client> c(is_ssl);
  380. c.m_client.set_tls_init_handler(bind(&OnTlsInit, ::_1));
  381. c.run(uri, wav_list, wav_ids, hotwords_);
  382. } else {
  383. WebsocketClient<websocketpp::config::asio_client> c(is_ssl);
  384. c.run(uri, wav_list, wav_ids, hotwords_);
  385. }
  386. });
  387. }
  388. for (auto& t : client_threads) {
  389. t.join();
  390. }
  391. }