sherpa-ncnn-ffmpeg.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. /**
  2. * Copyright (c) 2023 Xiaomi Corporation (authors: Fangjun Kuang)
  3. *
  4. * See LICENSE for clarification regarding multiple authors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include <signal.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <cctype> // std::tolower
  23. #include <string>
  24. #include "sherpa-ncnn/csrc/display.h"
  25. #include "sherpa-ncnn/csrc/recognizer.h"
  26. /*
  27. * The MIT License (MIT)
  28. *
  29. * Copyright (c) 2010 Nicolas George
  30. * Copyright (c) 2011 Stefano Sabatini
  31. * Copyright (c) 2012 Clément Bœsch
  32. *
  33. * Permission is hereby granted, free of charge, to any person obtaining a copy
  34. * of this software and associated documentation files (the "Software"), to deal
  35. * in the Software without restriction, including without limitation the rights
  36. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37. * copies of the Software, and to permit persons to whom the Software is
  38. * furnished to do so, subject to the following conditions:
  39. *
  40. * The above copyright notice and this permission notice shall be included in
  41. * all copies or substantial portions of the Software.
  42. *
  43. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  44. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  45. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  46. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  47. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  48. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  49. * THE SOFTWARE.
  50. */
  51. /**
  52. * @file audio decoding and filtering usage example
  53. * @example sherpa-ncnn-ffmpeg.c
  54. *
  55. * Demux, decode and filter audio input file, generate a raw audio
  56. * file to be played with ffplay.
  57. */
  58. #include <unistd.h>
  59. #ifdef __cplusplus
  60. extern "C" {
  61. #endif
  62. #include <libavcodec/avcodec.h>
  63. #include <libavfilter/buffersink.h>
  64. #include <libavfilter/buffersrc.h>
  65. #include <libavformat/avformat.h>
  66. #include <libavutil/channel_layout.h>
  67. #include <libavutil/opt.h>
  68. #include <libavutil/samplefmt.h>
  69. #ifdef __cplusplus
  70. }
  71. #endif
  72. static int32_t FFmpegOpenInputFile(AVFormatContext *ffmpeg_fmt_ctx,
  73. const char *filename,
  74. int32_t *ffmpeg_audio_stream_index) {
  75. int32_t ret;
  76. if ((ret = avformat_open_input(&ffmpeg_fmt_ctx, filename, NULL, NULL)) < 0) {
  77. av_log(NULL, AV_LOG_ERROR, "Cannot open input file %s, ret=%d\n", filename,
  78. ret);
  79. return ret;
  80. }
  81. if ((ret = avformat_find_stream_info(ffmpeg_fmt_ctx, NULL)) < 0) {
  82. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information, ret=%d\n", ret);
  83. return ret;
  84. }
  85. /* select the audio stream */
  86. enum AVMediaType type = AVMEDIA_TYPE_AUDIO;
  87. ret = av_find_best_stream(ffmpeg_fmt_ctx, type, -1, -1, NULL, 0);
  88. if (ret < 0) {
  89. av_log(NULL, AV_LOG_ERROR, "No audio stream in the input file, ret=%d\n",
  90. ret);
  91. return ret;
  92. }
  93. *ffmpeg_audio_stream_index = ret;
  94. return 0;
  95. }
  96. static int32_t FFmpegOpenDecoder(AVCodecContext *ffmpeg_dec_ctx,
  97. AVStream *stream, const AVCodec *dec) {
  98. if (!dec) {
  99. av_log(NULL, AV_LOG_ERROR, "Failed to find %d codec",
  100. stream->codecpar->codec_id);
  101. return AVERROR(EINVAL);
  102. }
  103. avcodec_parameters_to_context(ffmpeg_dec_ctx, stream->codecpar);
  104. /* init the audio decoder */
  105. int32_t ret;
  106. if ((ret = avcodec_open2(ffmpeg_dec_ctx, dec, NULL)) < 0) {
  107. av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder, ret=%d\n", ret);
  108. return ret;
  109. }
  110. return 0;
  111. }
  112. static int32_t FFmpegInitFilters(AVCodecContext *ffmpeg_dec_ctx,
  113. AVFilterGraph *ffmpeg_filter_graph,
  114. AVFilterContext **ffmpeg_buffersink_ctx,
  115. AVFilterContext **ffmpeg_buffersrc_ctx,
  116. AVRational time_base,
  117. const char *filters_descr) {
  118. /* buffer audio source: the decoded frames from the decoder will be inserted
  119. * here. */
  120. if (ffmpeg_dec_ctx->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC) {
  121. av_channel_layout_default(&ffmpeg_dec_ctx->ch_layout,
  122. ffmpeg_dec_ctx->ch_layout.nb_channels);
  123. }
  124. char args[512];
  125. int32_t ret =
  126. snprintf(args, sizeof(args),
  127. "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=",
  128. time_base.num, time_base.den, ffmpeg_dec_ctx->sample_rate,
  129. av_get_sample_fmt_name(ffmpeg_dec_ctx->sample_fmt));
  130. av_channel_layout_describe(&ffmpeg_dec_ctx->ch_layout, args + ret,
  131. sizeof(args) - ret);
  132. const AVFilter *abuffersrc = avfilter_get_by_name("abuffer");
  133. ret = avfilter_graph_create_filter(ffmpeg_buffersrc_ctx, abuffersrc, "in",
  134. args, NULL, ffmpeg_filter_graph);
  135. if (ret < 0) {
  136. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source, ret=%d\n",
  137. ret);
  138. return AVERROR(EINVAL);
  139. }
  140. /* buffer audio sink: to terminate the filter chain. */
  141. const AVFilter *abuffersink = avfilter_get_by_name("abuffersink");
  142. ret = avfilter_graph_create_filter(ffmpeg_buffersink_ctx, abuffersink, "out",
  143. NULL, NULL, ffmpeg_filter_graph);
  144. if (ret < 0) {
  145. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink, ret=%d\n",
  146. ret);
  147. return AVERROR(EINVAL);
  148. }
  149. static const enum AVSampleFormat out_sample_fmts[] = {AV_SAMPLE_FMT_S16,
  150. AV_SAMPLE_FMT_NONE};
  151. ret = av_opt_set_int_list(*ffmpeg_buffersink_ctx, "sample_fmts",
  152. out_sample_fmts, -1, AV_OPT_SEARCH_CHILDREN);
  153. if (ret < 0) {
  154. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format, ret=%d\n",
  155. ret);
  156. return AVERROR(EINVAL);
  157. }
  158. ret = av_opt_set(*ffmpeg_buffersink_ctx, "ch_layouts", "mono",
  159. AV_OPT_SEARCH_CHILDREN);
  160. if (ret < 0) {
  161. av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout, ret=%d\n",
  162. ret);
  163. return AVERROR(EINVAL);
  164. }
  165. static const int32_t out_sample_rates[] = {16000, -1};
  166. ret = av_opt_set_int_list(*ffmpeg_buffersink_ctx, "sample_rates",
  167. out_sample_rates, -1, AV_OPT_SEARCH_CHILDREN);
  168. if (ret < 0) {
  169. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate, ret=%d\n", ret);
  170. return AVERROR(EINVAL);
  171. }
  172. /*
  173. * Set the endpoints for the filter graph. The ffmpeg_filter_graph will
  174. * be linked to the graph described by filters_descr.
  175. */
  176. /*
  177. * The buffer source output must be connected to the input pad of
  178. * the first filter described by filters_descr; since the first
  179. * filter input label is not specified, it is set to "in" by
  180. * default.
  181. */
  182. auto outputs = std::unique_ptr<AVFilterInOut, void (*)(AVFilterInOut *)>(
  183. avfilter_inout_alloc(),
  184. [](AVFilterInOut *p) { avfilter_inout_free(&p); });
  185. if (outputs == nullptr) {
  186. av_log(NULL, AV_LOG_ERROR, "Cannot allocate memory for outputs");
  187. return AVERROR(EINVAL);
  188. }
  189. outputs->name = av_strdup("in");
  190. outputs->filter_ctx = *ffmpeg_buffersrc_ctx;
  191. outputs->pad_idx = 0;
  192. outputs->next = NULL;
  193. /*
  194. * The buffer sink input must be connected to the output pad of
  195. * the last filter described by filters_descr; since the last
  196. * filter output label is not specified, it is set to "out" by
  197. * default.
  198. */
  199. auto inputs = std::unique_ptr<AVFilterInOut, void (*)(AVFilterInOut *)>(
  200. avfilter_inout_alloc(),
  201. [](AVFilterInOut *p) { avfilter_inout_free(&p); });
  202. if (inputs == nullptr) {
  203. av_log(NULL, AV_LOG_ERROR, "Cannot allocate memory for inputs");
  204. return AVERROR(EINVAL);
  205. }
  206. inputs->name = av_strdup("out");
  207. inputs->filter_ctx = *ffmpeg_buffersink_ctx;
  208. inputs->pad_idx = 0;
  209. inputs->next = NULL;
  210. // The avfilter_graph_parse_ptr might change the pointer, so we need to
  211. // release inputs to inputs_ptr, then reset inputs_ptr to inputs. Note that
  212. // inputs_ptr might change after avfilter_graph_parse_ptr.
  213. AVFilterInOut *inputs_ptr = inputs.release();
  214. AVFilterInOut *outputs_ptr = outputs.release();
  215. ret = avfilter_graph_parse_ptr(ffmpeg_filter_graph, filters_descr,
  216. &inputs_ptr, &outputs_ptr, NULL);
  217. inputs.reset(inputs_ptr);
  218. outputs.reset(outputs_ptr);
  219. if (ret < 0) {
  220. av_log(NULL, AV_LOG_ERROR, "Cannot avfilter_graph_parse_ptr, ret=%d\n",
  221. ret);
  222. return AVERROR(EINVAL);
  223. }
  224. if ((ret = avfilter_graph_config(ffmpeg_filter_graph, NULL)) < 0) {
  225. av_log(NULL, AV_LOG_ERROR, "Cannot avfilter_graph_config, ret=%d\n", ret);
  226. return AVERROR(EINVAL);
  227. }
  228. /* Print summary of the sink buffer
  229. * Note: args buffer is reused to store channel layout string */
  230. const AVFilterLink *outlink;
  231. outlink = (*ffmpeg_buffersink_ctx)->inputs[0];
  232. av_channel_layout_describe(&outlink->ch_layout, args, sizeof(args));
  233. fprintf(
  234. stdout,
  235. "Event:FFmpeg: Detect audio stream ok, srate:%dHz fmt:%s chlayout:%s\n",
  236. (int)outlink->sample_rate,
  237. (char *)av_x_if_null(
  238. av_get_sample_fmt_name((AVSampleFormat)outlink->format), "?"),
  239. args);
  240. fflush(stdout);
  241. return ret;
  242. }
  243. static void FFmpegOnDecodedFrame(const AVFrame *frame,
  244. const sherpa_ncnn::Recognizer &recognizer,
  245. sherpa_ncnn::Stream *s,
  246. sherpa_ncnn::Display *display,
  247. std::string *last_text, int32_t *segment_index,
  248. int32_t *zero_samples) {
  249. if (!frame->nb_samples) {
  250. return;
  251. }
  252. // Convert the PCM from int16_t to float. Note that K2 sample is [-1, 1], so
  253. // we need to divide by 32768.
  254. #define MAX_SAMPLES 3200 // 0.2 s. Sample rate is fixed to 16 kHz
  255. static float samples[MAX_SAMPLES];
  256. int32_t nb_samples = 0;
  257. if (frame->nb_samples > MAX_SAMPLES) {
  258. av_log(NULL, AV_LOG_ERROR, "Too many samples: %d\n", frame->nb_samples);
  259. return;
  260. }
  261. if (1) {
  262. const int16_t *p = (int16_t *)frame->data[0];
  263. for (int32_t i = 0; i < frame->nb_samples; i++) {
  264. // ASD(Active speaker detection) detection.
  265. if (p[i] == 0) {
  266. (*zero_samples)++;
  267. }
  268. // Convert to float [-1, 1].
  269. samples[nb_samples++] = p[i] / 32768.;
  270. }
  271. }
  272. // Feed samples to K2, which accepts any number of samples.
  273. s->AcceptWaveform(16000, samples, nb_samples);
  274. while (recognizer.IsReady(s)) {
  275. recognizer.DecodeStream(s);
  276. }
  277. bool is_endpoint = recognizer.IsEndpoint(s);
  278. auto text = recognizer.GetResult(s).text;
  279. if (!text.empty() && *last_text != text) {
  280. *last_text = text;
  281. std::transform(text.begin(), text.end(), text.begin(),
  282. [](auto c) { return std::tolower(c); });
  283. display->Print(*segment_index, text);
  284. }
  285. if (is_endpoint) {
  286. if (!text.empty()) {
  287. (*segment_index)++;
  288. }
  289. recognizer.Reset(s);
  290. }
  291. }
  292. static inline char *FFmpegAvError2String(int32_t errnum) {
  293. static char str[AV_ERROR_MAX_STRING_SIZE];
  294. memset(str, 0, sizeof(str));
  295. return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
  296. }
  297. // When stream unpublish, use this signal to notify application.
  298. static int32_t signal_unpublish_sigusr1 = 0;
  299. static void Handler(int32_t sig) {
  300. if (sig == SIGUSR1) {
  301. fprintf(stdout, "\nEvent:Signal: Got signal %d\n", sig);
  302. fflush(stdout);
  303. signal_unpublish_sigusr1 = 1;
  304. return;
  305. }
  306. fprintf(stdout, "\nEvent:Signal: Caught Ctrl + C. Exiting...\n");
  307. fflush(stdout);
  308. signal(sig, SIG_DFL);
  309. raise(sig);
  310. };
  311. #define SET_STRING_BY_ENV(config, key) \
  312. if (getenv(key)) { \
  313. config = getenv(key); \
  314. }
  315. #define SET_CONFIG_BY_ENV(config, key, required) \
  316. config = ""; \
  317. SET_STRING_BY_ENV(config, key); \
  318. if (!(config).empty() && required) { \
  319. parsed_required_envs++; \
  320. }
  321. #define SET_INTEGER_BY_ENV(config, key) \
  322. { \
  323. std::string val; \
  324. SET_STRING_BY_ENV(val, "SHERPA_NCNN_ASD_ENDPOINTS"); \
  325. if (!val.empty() && ::atoi(val.c_str()) > 0) { \
  326. config = ::atoi(val.c_str()); \
  327. } \
  328. }
  329. static int32_t ParseConfigFromENV(sherpa_ncnn::RecognizerConfig *config,
  330. std::string *input_url) {
  331. int32_t parsed_required_envs = 0;
  332. sherpa_ncnn::ModelConfig &mc = config->model_config;
  333. SET_CONFIG_BY_ENV(mc.tokens, "SHERPA_NCNN_TOKENS", true);
  334. SET_CONFIG_BY_ENV(mc.encoder_param, "SHERPA_NCNN_ENCODER_PARAM", true);
  335. SET_CONFIG_BY_ENV(mc.encoder_bin, "SHERPA_NCNN_ENCODER_BIN", true);
  336. SET_CONFIG_BY_ENV(mc.decoder_param, "SHERPA_NCNN_DECODER_PARAM", true);
  337. SET_CONFIG_BY_ENV(mc.decoder_bin, "SHERPA_NCNN_DECODER_BIN", true);
  338. SET_CONFIG_BY_ENV(mc.joiner_param, "SHERPA_NCNN_JOINER_PARAM", true);
  339. SET_CONFIG_BY_ENV(mc.joiner_bin, "SHERPA_NCNN_JOINER_BIN", true);
  340. SET_CONFIG_BY_ENV(*input_url, "SHERPA_NCNN_INPUT_URL", true);
  341. std::string val;
  342. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_NUM_THREADS", false);
  343. if (!val.empty()) {
  344. if (atoi(val.c_str()) <= 0) {
  345. fprintf(stderr, "Invalid SHERPA_NCNN_NUM_THREADS=%s\n", val.c_str());
  346. return -1;
  347. }
  348. mc.encoder_opt.num_threads = atoi(val.c_str());
  349. mc.decoder_opt.num_threads = atoi(val.c_str());
  350. mc.joiner_opt.num_threads = atoi(val.c_str());
  351. }
  352. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_METHOD", false);
  353. if (!val.empty()) {
  354. if (val != "greedy_search" && val != "modified_beam_search") {
  355. fprintf(stderr, "Invalid SHERPA_NCNN_METHOD=%s\n", val.c_str());
  356. return -1;
  357. }
  358. config->decoder_config.method = val;
  359. }
  360. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_ENABLE_ENDPOINT", false);
  361. if (!val.empty()) {
  362. std::transform(val.begin(), val.end(), val.begin(),
  363. [](auto c) { return std::tolower(c); });
  364. config->enable_endpoint = val == "true" || val == "on";
  365. }
  366. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_RULE1_MIN_TRAILING_SILENCE", false);
  367. if (!val.empty()) {
  368. if (::atof(val.c_str()) <= 0) {
  369. fprintf(stderr, "Invalid SHERPA_NCNN_RULE1_MIN_TRAILING_SILENCE=%s\n",
  370. val.c_str());
  371. return -1;
  372. }
  373. config->endpoint_config.rule1.min_trailing_silence = ::atof(val.c_str());
  374. }
  375. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_RULE2_MIN_TRAILING_SILENCE", false);
  376. if (!val.empty()) {
  377. if (::atof(val.c_str()) <= 0) {
  378. fprintf(stderr, "Invalid SHERPA_NCNN_RULE2_MIN_TRAILING_SILENCE=%s\n",
  379. val.c_str());
  380. return -1;
  381. }
  382. config->endpoint_config.rule2.min_trailing_silence = ::atof(val.c_str());
  383. }
  384. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_RULE3_MIN_UTTERANCE_LENGTH", false);
  385. if (!val.empty()) {
  386. if (::atof(val.c_str()) <= 0) {
  387. fprintf(stderr, "Invalid SHERPA_NCNN_RULE3_MIN_UTTERANCE_LENGTH=%s\n",
  388. val.c_str());
  389. return -1;
  390. }
  391. config->endpoint_config.rule3.min_utterance_length = ::atof(val.c_str());
  392. }
  393. return parsed_required_envs;
  394. }
  395. static void SetDefaultConfigurations(sherpa_ncnn::RecognizerConfig *config) {
  396. int32_t num_threads = 4;
  397. config->model_config.encoder_opt.num_threads = num_threads;
  398. config->model_config.decoder_opt.num_threads = num_threads;
  399. config->model_config.joiner_opt.num_threads = num_threads;
  400. config->enable_endpoint = true;
  401. config->endpoint_config.rule1.min_trailing_silence = 2.4;
  402. config->endpoint_config.rule2.min_trailing_silence = 1.2;
  403. config->endpoint_config.rule3.min_utterance_length = 300;
  404. const float expected_sampling_rate = 16000;
  405. config->feat_config.sampling_rate = expected_sampling_rate;
  406. config->feat_config.feature_dim = 80;
  407. }
  408. static int32_t OverwriteConfigByCLI(int32_t argc, char **argv,
  409. sherpa_ncnn::RecognizerConfig *config,
  410. std::string *input_url) {
  411. if (argc > 1) config->model_config.tokens = argv[1];
  412. if (argc > 2) config->model_config.encoder_param = argv[2];
  413. if (argc > 3) config->model_config.encoder_bin = argv[3];
  414. if (argc > 4) config->model_config.decoder_param = argv[4];
  415. if (argc > 5) config->model_config.decoder_bin = argv[5];
  416. if (argc > 6) config->model_config.joiner_param = argv[6];
  417. if (argc > 7) config->model_config.joiner_bin = argv[7];
  418. if (argc > 8) *input_url = argv[8];
  419. if (argc >= 10 && atoi(argv[9]) > 0) {
  420. int32_t num_threads = atoi(argv[9]);
  421. config->model_config.encoder_opt.num_threads = num_threads;
  422. config->model_config.decoder_opt.num_threads = num_threads;
  423. config->model_config.joiner_opt.num_threads = num_threads;
  424. }
  425. if (argc == 11) {
  426. std::string val = argv[10];
  427. if (val != "greedy_search" && val != "modified_beam_search") {
  428. fprintf(stderr, "Invalid SHERPA_NCNN_METHOD=%s\n", val.c_str());
  429. return -1;
  430. }
  431. config->decoder_config.method = val;
  432. }
  433. return 0;
  434. }
  435. // A simple display, without window support, doesn't rewrite current line.
  436. // It only output the new text, which only works in greedy_search mode.
  437. // It doesn't support modified_beam_search mode, which might change the
  438. // generated text.
  439. class SimpleDisplay : public sherpa_ncnn::Display {
  440. public:
  441. SimpleDisplay(std::string label) {
  442. label_ = label.empty() ? "" : label + ":";
  443. }
  444. void Print(int32_t segment_id, const std::string &s) {
  445. if (last_segment_ != segment_id) {
  446. last_segment_ = segment_id;
  447. last_text_ = "";
  448. if (segment_id) {
  449. fprintf(stderr, "\n");
  450. }
  451. fprintf(stderr, "%s%d:", label_.c_str(), segment_id);
  452. if (!s.empty() && s.at(0) != ' ') {
  453. fprintf(stderr, " ");
  454. }
  455. }
  456. if (s.length() > last_text_.length()) {
  457. std::string tmp(s.begin() + last_text_.length(), s.end());
  458. fprintf(stderr, "%s", tmp.c_str());
  459. } else {
  460. fprintf(stderr, "%s", s.c_str());
  461. }
  462. last_text_ = s;
  463. }
  464. private:
  465. std::string label_;
  466. std::string last_text_;
  467. int32_t last_segment_ = -1;
  468. };
  469. std::unique_ptr<sherpa_ncnn::Display> CreateDisplay() {
  470. std::string val;
  471. SET_STRING_BY_ENV(val, "SHERPA_NCNN_SIMPLE_DISLAY");
  472. std::transform(val.begin(), val.end(), val.begin(),
  473. [](auto c) { return std::tolower(c); });
  474. if (val == "on" || val == "true") {
  475. std::string label;
  476. SET_STRING_BY_ENV(label, "SHERPA_NCNN_DISPLAY_LABEL");
  477. return std::make_unique<SimpleDisplay>(label);
  478. } else {
  479. return std::make_unique<sherpa_ncnn::Display>();
  480. }
  481. }
  482. int32_t main(int32_t argc, char **argv) {
  483. // Set the default values for config.
  484. sherpa_ncnn::RecognizerConfig config;
  485. SetDefaultConfigurations(&config);
  486. // Load and overwrite config from environment variables.
  487. std::string input_url;
  488. int32_t parsed_required_envs = ParseConfigFromENV(&config, &input_url);
  489. if (parsed_required_envs < 0) {
  490. exit(-1);
  491. }
  492. // Error if not set by neither environment variables nor CLI.
  493. if (parsed_required_envs < 8 && (argc < 9 || argc > 11)) {
  494. const char *usage = R"usage(
  495. Usage:
  496. ./bin/sherpa-ncnn-ffmpeg \
  497. /path/to/tokens.txt \
  498. /path/to/encoder.ncnn.param \
  499. /path/to/encoder.ncnn.bin \
  500. /path/to/decoder.ncnn.param \
  501. /path/to/decoder.ncnn.bin \
  502. /path/to/joiner.ncnn.param \
  503. /path/to/joiner.ncnn.bin \
  504. ffmpeg-input-url \
  505. [num_threads] [decode_method, can be greedy_search/modified_beam_search]
  506. Or configure by environment variables:
  507. SHERPA_NCNN_TOKENS=/path/to/tokens.txt \
  508. SHERPA_NCNN_ENCODER_PARAM=/path/to/encoder_jit_trace-pnnx.ncnn.param \
  509. SHERPA_NCNN_ENCODER_BIN=/path/to/encoder_jit_trace-pnnx.ncnn.bin \
  510. SHERPA_NCNN_DECODER_PARAM=/path/to/decoder_jit_trace-pnnx.ncnn.param \
  511. SHERPA_NCNN_DECODER_BIN=/path/to/decoder_jit_trace-pnnx.ncnn.bin \
  512. SHERPA_NCNN_JOINER_PARAM=/path/to/joiner_jit_trace-pnnx.ncnn.param \
  513. SHERPA_NCNN_JOINER_BIN=/path/to/joiner_jit_trace-pnnx.ncnn.bin \
  514. SHERPA_NCNN_INPUT_URL=ffmpeg-input-url \
  515. SHERPA_NCNN_NUM_THREADS=4 \
  516. SHERPA_NCNN_METHOD=greedy_search|modified_beam_search \
  517. SHERPA_NCNN_ENABLE_ENDPOINT=on|off \
  518. SHERPA_NCNN_RULE1_MIN_TRAILING_SILENCE=2.4 \
  519. SHERPA_NCNN_RULE2_MIN_TRAILING_SILENCE=1.2 \
  520. SHERPA_NCNN_RULE3_MIN_UTTERANCE_LENGTH=300 \
  521. SHERPA_NCNN_SIMPLE_DISLAY=on|off \
  522. SHERPA_NCNN_DISPLAY_LABEL=Data \
  523. SHERPA_NCNN_ASD_ENDPOINTS=3 \
  524. SHERPA_NCNN_ASD_SAMPLES=10 \
  525. ./bin/sherpa-ncnn-ffmpeg
  526. Please refer to
  527. https://k2-fsa.github.io/sherpa/ncnn/pretrained_models/index.html
  528. for a list of pre-trained models to download.
  529. )usage";
  530. fprintf(stderr, "%s\n", usage);
  531. fprintf(stderr, "argc, %d\n", argc);
  532. return -1;
  533. }
  534. signal(SIGINT, Handler);
  535. signal(SIGUSR1, Handler);
  536. // Overwrite the config by CLI.
  537. if (OverwriteConfigByCLI(argc, argv, &config, &input_url)) {
  538. exit(-1);
  539. }
  540. fprintf(stdout, "Event:K2: Config is %s\n", config.ToString().c_str());
  541. fflush(stdout);
  542. sherpa_ncnn::Recognizer recognizer(config);
  543. auto s = recognizer.CreateStream();
  544. fprintf(stdout, "Event:K2: Create recognizer ok\n");
  545. fflush(stdout);
  546. // Initialize FFmpeg framework.
  547. auto ffmpeg_fmt_ctx =
  548. std::unique_ptr<AVFormatContext, void (*)(AVFormatContext *)>(
  549. avformat_alloc_context(), [](auto p) { avformat_close_input(&p); });
  550. int32_t ret;
  551. fprintf(stdout, "Event:FFmpeg: Open input %s\n", input_url.c_str());
  552. fflush(stdout);
  553. int32_t ffmpeg_audio_stream_index = -1;
  554. if ((ret = FFmpegOpenInputFile(ffmpeg_fmt_ctx.get(), input_url.c_str(),
  555. &ffmpeg_audio_stream_index)) < 0) {
  556. fprintf(stderr, "Open input file %s failed, ret=%d\n", input_url.c_str(),
  557. ret);
  558. exit(1);
  559. }
  560. fprintf(stdout, "Event:FFmpeg: Open input ok, %s\n", input_url.c_str());
  561. fflush(stdout);
  562. // Create decoder context.
  563. AVStream *stream = ffmpeg_fmt_ctx->streams[ffmpeg_audio_stream_index];
  564. // We should use dec to initialize the decoder context, because it uses
  565. // different flags set.
  566. const AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id);
  567. auto ffmpeg_dec_ctx =
  568. std::unique_ptr<AVCodecContext, void (*)(AVCodecContext *)>(
  569. avcodec_alloc_context3(dec),
  570. [](auto p) { avcodec_free_context(&p); });
  571. if ((ret = FFmpegOpenDecoder(ffmpeg_dec_ctx.get(), stream, dec)) < 0) {
  572. fprintf(stderr, "Open decoder failed, ret=%d\n", ret);
  573. exit(1);
  574. }
  575. auto ffmpeg_filter_graph =
  576. std::unique_ptr<AVFilterGraph, void (*)(AVFilterGraph *)>(
  577. avfilter_graph_alloc(), [](auto p) { avfilter_graph_free(&p); });
  578. AVFilterContext *ffmpeg_buffersink_ctx;
  579. AVFilterContext *ffmpeg_buffersrc_ctx;
  580. static const char *ffmpeg_filter_descr =
  581. "aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono";
  582. if ((ret = FFmpegInitFilters(ffmpeg_dec_ctx.get(), ffmpeg_filter_graph.get(),
  583. &ffmpeg_buffersink_ctx, &ffmpeg_buffersrc_ctx,
  584. stream->time_base, ffmpeg_filter_descr)) < 0) {
  585. fprintf(stderr, "Init filters %s failed, ret=%d\n", ffmpeg_filter_descr,
  586. ret);
  587. exit(1);
  588. }
  589. int32_t asd_endpoints = 0, asd_samples = 0;
  590. SET_INTEGER_BY_ENV(asd_endpoints, "SHERPA_NCNN_ASD_ENDPOINTS");
  591. SET_INTEGER_BY_ENV(asd_samples, "SHERPA_NCNN_ASD_SAMPLES");
  592. auto packet = std::unique_ptr<AVPacket, void (*)(AVPacket *)>(
  593. av_packet_alloc(), [](auto p) { av_packet_free(&p); });
  594. auto frame = std::unique_ptr<AVFrame, void (*)(AVFrame *)>(
  595. av_frame_alloc(), [](auto p) { av_frame_free(&p); });
  596. auto filt_frame = std::unique_ptr<AVFrame, void (*)(AVFrame *)>(
  597. av_frame_alloc(), [](auto p) { av_frame_free(&p); });
  598. if (packet == nullptr || frame == nullptr || filt_frame == nullptr) {
  599. fprintf(stderr, "Could not allocate frame or packet\n");
  600. exit(1);
  601. }
  602. std::string last_text;
  603. int32_t segment_index = 0, zero_samples = 0, asd_segment = 0;
  604. std::unique_ptr<sherpa_ncnn::Display> display = CreateDisplay();
  605. while (ret >= 0) {
  606. if ((ret = av_read_frame(ffmpeg_fmt_ctx.get(), packet.get())) < 0) {
  607. av_log(NULL, AV_LOG_ERROR, "Error reading frame ret=%d\n", ret);
  608. break;
  609. }
  610. // The packet must be freed with av_packet_unref() when it is no longer
  611. // needed.
  612. auto packet_unref = std::unique_ptr<AVPacket, void (*)(AVPacket *)>(
  613. packet.get(), [](auto p) { av_packet_unref(p); });
  614. (void)packet_unref;
  615. // Reset the ASD(Active speaker detection) segment when stream unpublish.
  616. if (signal_unpublish_sigusr1) {
  617. signal_unpublish_sigusr1 = 0;
  618. if (asd_segment != segment_index) {
  619. asd_segment = segment_index;
  620. }
  621. }
  622. // ASD(Active speaker detection), note that 16000 samples is 1s.
  623. if (asd_samples && zero_samples > asd_samples * 16000) {
  624. // When unpublished, there might be some left samples in buffer.
  625. if (asd_endpoints && segment_index - asd_segment < asd_endpoints) {
  626. fprintf(stdout, "\nEvent:FFmpeg: Silence, incorrect microphone?\n");
  627. fflush(stdout);
  628. }
  629. zero_samples = 0;
  630. }
  631. // Ignore packets except audio stream.
  632. if (packet->stream_index != ffmpeg_audio_stream_index) {
  633. continue;
  634. }
  635. ret = avcodec_send_packet(ffmpeg_dec_ctx.get(), packet.get());
  636. if (ret < 0) {
  637. av_log(NULL, AV_LOG_ERROR, "Error feed decoder packet, ret=%d\n", ret);
  638. break;
  639. }
  640. while (ret >= 0) {
  641. ret = avcodec_receive_frame(ffmpeg_dec_ctx.get(), frame.get());
  642. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  643. ret = 0;
  644. break;
  645. } else if (ret < 0) {
  646. av_log(NULL, AV_LOG_ERROR, "Error dec receive frame, ret=%d\n", ret);
  647. break;
  648. }
  649. // Always free the frame with av_frame_unref() when it is no longer
  650. // needed.
  651. auto frame_unref = std::unique_ptr<AVFrame, void (*)(AVFrame *)>(
  652. frame.get(), [](auto p) { av_frame_unref(p); });
  653. (void)frame_unref;
  654. /* push the audio data from decoded frame into the filtergraph */
  655. ret = av_buffersrc_add_frame_flags(ffmpeg_buffersrc_ctx, frame.get(),
  656. AV_BUFFERSRC_FLAG_KEEP_REF);
  657. if (ret < 0) {
  658. av_log(NULL, AV_LOG_ERROR, "Error filter feed frame, ret=%d\n", ret);
  659. break;
  660. }
  661. /* pull filtered audio from the filtergraph */
  662. while (ret >= 0) {
  663. ret = av_buffersink_get_frame(ffmpeg_buffersink_ctx, filt_frame.get());
  664. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  665. ret = 0;
  666. break;
  667. }
  668. if (ret < 0) {
  669. fprintf(stderr, "Error get frame, ret=%d\n", ret);
  670. break;
  671. }
  672. // The filt_frame is an allocated frame that will be filled with data.
  673. // The data must be freed using av_frame_unref() / av_frame_free()
  674. auto filt_frame_unref = std::unique_ptr<AVFrame, void (*)(AVFrame *)>(
  675. filt_frame.get(), [](auto p) { av_frame_unref(p); });
  676. (void)filt_frame_unref;
  677. FFmpegOnDecodedFrame(filt_frame.get(), recognizer, s.get(),
  678. display.get(), &last_text, &segment_index,
  679. &zero_samples);
  680. }
  681. }
  682. }
  683. // Add some tail padding
  684. if (1) {
  685. float tail_paddings[4800] = {0}; // 0.3 seconds at 16 kHz sample rate
  686. s->AcceptWaveform(16000, tail_paddings, 4800);
  687. s->InputFinished();
  688. while (recognizer.IsReady(s.get())) {
  689. recognizer.DecodeStream(s.get());
  690. }
  691. auto text = recognizer.GetResult(s.get()).text;
  692. if (!text.empty() && last_text != text) {
  693. last_text = text;
  694. std::transform(text.begin(), text.end(), text.begin(),
  695. [](auto c) { return std::tolower(c); });
  696. display->Print(segment_index, text);
  697. }
  698. }
  699. if (ret < 0 && ret != AVERROR_EOF) {
  700. fprintf(stderr, "Error occurred: %s\n", FFmpegAvError2String(ret));
  701. exit(1);
  702. }
  703. return 0;
  704. }