funasr-wss-client-2pass.cpp 15 KB

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