funasr-wss-client.cpp 16 KB

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