funasr-ws-client.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. // Usage: websocketclient server_ip port wav_path threads_num
  8. #define ASIO_STANDALONE 1
  9. #include <websocketpp/client.hpp>
  10. #include <websocketpp/common/thread.hpp>
  11. #include <websocketpp/config/asio_client.hpp>
  12. #include <fstream>
  13. #include <atomic>
  14. #include <glog/logging.h>
  15. #include "audio.h"
  16. #include "nlohmann/json.hpp"
  17. #include "tclap/CmdLine.h"
  18. /**
  19. * Define a semi-cross platform helper method that waits/sleeps for a bit.
  20. */
  21. void WaitABit() {
  22. #ifdef WIN32
  23. Sleep(1000);
  24. #else
  25. sleep(1);
  26. #endif
  27. }
  28. std::atomic<int> wav_index(0);
  29. bool IsTargetFile(const std::string& filename, const std::string target) {
  30. std::size_t pos = filename.find_last_of(".");
  31. if (pos == std::string::npos) {
  32. return false;
  33. }
  34. std::string extension = filename.substr(pos + 1);
  35. return (extension == target);
  36. }
  37. typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
  38. typedef websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context> context_ptr;
  39. using websocketpp::lib::bind;
  40. using websocketpp::lib::placeholders::_1;
  41. using websocketpp::lib::placeholders::_2;
  42. context_ptr OnTlsInit(websocketpp::connection_hdl) {
  43. context_ptr ctx = websocketpp::lib::make_shared<asio::ssl::context>(
  44. asio::ssl::context::sslv23);
  45. try {
  46. ctx->set_options(
  47. asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 |
  48. asio::ssl::context::no_sslv3 | asio::ssl::context::single_dh_use);
  49. } catch (std::exception& e) {
  50. std::cout << e.what() << std::endl;
  51. }
  52. return ctx;
  53. }
  54. // template for tls or not config
  55. template <typename T>
  56. class WebsocketClient {
  57. public:
  58. // typedef websocketpp::client<T> client;
  59. // typedef websocketpp::client<websocketpp::config::asio_tls_client>
  60. // wss_client;
  61. typedef websocketpp::lib::lock_guard<websocketpp::lib::mutex> scoped_lock;
  62. WebsocketClient(int is_ssl) : m_open(false), m_done(false) {
  63. // set up access channels to only log interesting things
  64. m_client.clear_access_channels(websocketpp::log::alevel::all);
  65. m_client.set_access_channels(websocketpp::log::alevel::connect);
  66. m_client.set_access_channels(websocketpp::log::alevel::disconnect);
  67. m_client.set_access_channels(websocketpp::log::alevel::app);
  68. // Initialize the Asio transport policy
  69. m_client.init_asio();
  70. // Bind the handlers we are using
  71. using websocketpp::lib::bind;
  72. using websocketpp::lib::placeholders::_1;
  73. m_client.set_open_handler(bind(&WebsocketClient::on_open, this, _1));
  74. m_client.set_close_handler(bind(&WebsocketClient::on_close, 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. std::cout << "on_message = " << payload << std::endl;
  88. }
  89. }
  90. // This method will block until the connection is complete
  91. void run(const std::string& uri, const std::vector<string>& wav_list, const std::vector<string>& wav_ids) {
  92. // Create a new connection to the given URI
  93. websocketpp::lib::error_code ec;
  94. typename websocketpp::client<T>::connection_ptr con =
  95. m_client.get_connection(uri, ec);
  96. if (ec) {
  97. m_client.get_alog().write(websocketpp::log::alevel::app,
  98. "Get Connection Error: " + ec.message());
  99. return;
  100. }
  101. // Grab a handle for this connection so we can talk to it in a thread
  102. // safe manor after the event loop starts.
  103. m_hdl = con->get_handle();
  104. // Queue the connection. No DNS queries or network connections will be
  105. // made until the io_service event loop is run.
  106. m_client.connect(con);
  107. // Create a thread to run the ASIO io_service event loop
  108. websocketpp::lib::thread asio_thread(&websocketpp::client<T>::run,
  109. &m_client);
  110. while(true){
  111. int i = wav_index.fetch_add(1);
  112. if (i >= wav_list.size()) {
  113. break;
  114. }
  115. send_wav_data(wav_list[i], wav_ids[i]);
  116. }
  117. WaitABit();
  118. m_client.close(m_hdl,websocketpp::close::status::going_away, "", ec);
  119. if (ec) {
  120. std::cout << "> Error closing connection " << ec.message() << std::endl;
  121. }
  122. //send_wav_data();
  123. asio_thread.join();
  124. }
  125. // The open handler will signal that we are ready to start sending data
  126. void on_open(websocketpp::connection_hdl) {
  127. m_client.get_alog().write(websocketpp::log::alevel::app,
  128. "Connection opened, starting data!");
  129. scoped_lock guard(m_lock);
  130. m_open = true;
  131. }
  132. // The close handler will signal that we should stop sending data
  133. void on_close(websocketpp::connection_hdl) {
  134. m_client.get_alog().write(websocketpp::log::alevel::app,
  135. "Connection closed, stopping data!");
  136. scoped_lock guard(m_lock);
  137. m_done = true;
  138. }
  139. // The fail handler will signal that we should stop sending data
  140. void on_fail(websocketpp::connection_hdl) {
  141. m_client.get_alog().write(websocketpp::log::alevel::app,
  142. "Connection failed, stopping data!");
  143. scoped_lock guard(m_lock);
  144. m_done = true;
  145. }
  146. // send wav to server
  147. void send_wav_data(string wav_path, string wav_id) {
  148. uint64_t count = 0;
  149. std::stringstream val;
  150. funasr::Audio audio(1);
  151. int32_t sampling_rate = 16000;
  152. if(IsTargetFile(wav_path.c_str(), "wav")){
  153. int32_t sampling_rate = -1;
  154. if(!audio.LoadWav(wav_path.c_str(), &sampling_rate))
  155. return ;
  156. }else if(IsTargetFile(wav_path.c_str(), "pcm")){
  157. if (!audio.LoadPcmwav(wav_path.c_str(), &sampling_rate))
  158. return ;
  159. }else{
  160. printf("Wrong wav extension");
  161. exit(-1);
  162. }
  163. float* buff;
  164. int len;
  165. int flag = 0;
  166. bool wait = false;
  167. while (1) {
  168. {
  169. scoped_lock guard(m_lock);
  170. // If the connection has been closed, stop generating data
  171. if (m_done) {
  172. break;
  173. }
  174. // If the connection hasn't been opened yet wait a bit and retry
  175. if (!m_open) {
  176. wait = true;
  177. } else {
  178. break;
  179. }
  180. }
  181. if (wait) {
  182. std::cout << "wait.." << m_open << std::endl;
  183. WaitABit();
  184. continue;
  185. }
  186. }
  187. websocketpp::lib::error_code ec;
  188. nlohmann::json jsonbegin;
  189. nlohmann::json chunk_size = nlohmann::json::array();
  190. chunk_size.push_back(5);
  191. chunk_size.push_back(0);
  192. chunk_size.push_back(5);
  193. jsonbegin["chunk_size"] = chunk_size;
  194. jsonbegin["chunk_interval"] = 10;
  195. jsonbegin["wav_name"] = wav_id;
  196. jsonbegin["is_speaking"] = true;
  197. m_client.send(m_hdl, jsonbegin.dump(), websocketpp::frame::opcode::text,
  198. ec);
  199. // fetch wav data use asr engine api
  200. while (audio.Fetch(buff, len, flag) > 0) {
  201. short iArray[len];
  202. // convert float -1,1 to short -32768,32767
  203. for (size_t i = 0; i < len; ++i) {
  204. iArray[i] = (short)(buff[i] * 32767);
  205. }
  206. // send data to server
  207. m_client.send(m_hdl, iArray, len * sizeof(short),
  208. websocketpp::frame::opcode::binary, ec);
  209. std::cout << "sended data len=" << len * sizeof(short) << std::endl;
  210. // The most likely error that we will get is that the connection is
  211. // not in the right state. Usually this means we tried to send a
  212. // message to a connection that was closed or in the process of
  213. // closing. While many errors here can be easily recovered from,
  214. // in this simple example, we'll stop the data loop.
  215. if (ec) {
  216. m_client.get_alog().write(websocketpp::log::alevel::app,
  217. "Send Error: " + ec.message());
  218. break;
  219. }
  220. WaitABit();
  221. }
  222. nlohmann::json jsonresult;
  223. jsonresult["is_speaking"] = false;
  224. m_client.send(m_hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  225. ec);
  226. WaitABit();
  227. }
  228. websocketpp::client<T> m_client;
  229. private:
  230. websocketpp::connection_hdl m_hdl;
  231. websocketpp::lib::mutex m_lock;
  232. bool m_open;
  233. bool m_done;
  234. };
  235. int main(int argc, char* argv[]) {
  236. google::InitGoogleLogging(argv[0]);
  237. FLAGS_logtostderr = true;
  238. TCLAP::CmdLine cmd("funasr-ws-client", ' ', "1.0");
  239. TCLAP::ValueArg<std::string> server_ip_("", "server-ip", "server-ip", true,
  240. "127.0.0.1", "string");
  241. TCLAP::ValueArg<std::string> port_("", "port", "port", true, "8889", "string");
  242. TCLAP::ValueArg<std::string> wav_path_("", "wav-path",
  243. "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)",
  244. true, "", "string");
  245. TCLAP::ValueArg<int> thread_num_("", "thread-num", "thread-num",
  246. false, 1, "int");
  247. TCLAP::ValueArg<int> is_ssl_(
  248. "", "is-ssl", "is-ssl is 1 means use wss connection, or use ws connection",
  249. false, 0, "int");
  250. cmd.add(server_ip_);
  251. cmd.add(port_);
  252. cmd.add(wav_path_);
  253. cmd.add(thread_num_);
  254. cmd.add(is_ssl_);
  255. cmd.parse(argc, argv);
  256. std::string server_ip = server_ip_.getValue();
  257. std::string port = port_.getValue();
  258. std::string wav_path = wav_path_.getValue();
  259. int threads_num = thread_num_.getValue();
  260. int is_ssl = is_ssl_.getValue();
  261. std::vector<websocketpp::lib::thread> client_threads;
  262. std::string uri = "";
  263. if (is_ssl == 1) {
  264. uri = "wss://" + server_ip + ":" + port;
  265. } else {
  266. uri = "ws://" + server_ip + ":" + port;
  267. }
  268. // read wav_path
  269. std::vector<string> wav_list;
  270. std::vector<string> wav_ids;
  271. string default_id = "wav_default_id";
  272. if(IsTargetFile(wav_path, "wav") || IsTargetFile(wav_path, "pcm")){
  273. wav_list.emplace_back(wav_path);
  274. wav_ids.emplace_back(default_id);
  275. }
  276. else if(IsTargetFile(wav_path, "scp")){
  277. ifstream in(wav_path);
  278. if (!in.is_open()) {
  279. printf("Failed to open scp file");
  280. return 0;
  281. }
  282. string line;
  283. while(getline(in, line))
  284. {
  285. istringstream iss(line);
  286. string column1, column2;
  287. iss >> column1 >> column2;
  288. wav_list.emplace_back(column2);
  289. wav_ids.emplace_back(column1);
  290. }
  291. in.close();
  292. }else{
  293. printf("Please check the wav extension!");
  294. exit(-1);
  295. }
  296. for (size_t i = 0; i < threads_num; i++) {
  297. client_threads.emplace_back([uri, wav_list, wav_ids, is_ssl]() {
  298. if (is_ssl == 1) {
  299. WebsocketClient<websocketpp::config::asio_tls_client> c(is_ssl);
  300. c.m_client.set_tls_init_handler(bind(&OnTlsInit, ::_1));
  301. c.run(uri, wav_list, wav_ids);
  302. } else {
  303. WebsocketClient<websocketpp::config::asio_client> c(is_ssl);
  304. c.run(uri, wav_list, wav_ids);
  305. }
  306. });
  307. }
  308. for (auto& t : client_threads) {
  309. t.join();
  310. }
  311. }