sherpa-ncnn-ffmpeg.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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 const char *filter_descr =
  73. "aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono";
  74. static AVFormatContext *fmt_ctx;
  75. static AVCodecContext *dec_ctx;
  76. AVFilterContext *buffersink_ctx;
  77. AVFilterContext *buffersrc_ctx;
  78. AVFilterGraph *filter_graph;
  79. static int32_t audio_stream_index = -1;
  80. static int32_t FFmpegOpenInputFile(const char *filename) {
  81. const AVCodec *dec;
  82. int32_t ret;
  83. if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
  84. av_log(NULL, AV_LOG_ERROR, "Cannot open input file %s\n", filename);
  85. return ret;
  86. }
  87. if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  88. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  89. return ret;
  90. }
  91. /* select the audio stream */
  92. ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
  93. if (ret < 0) {
  94. av_log(NULL, AV_LOG_ERROR,
  95. "Cannot find an audio stream in the input file\n");
  96. return ret;
  97. }
  98. audio_stream_index = ret;
  99. /* create decoding context */
  100. dec_ctx = avcodec_alloc_context3(dec);
  101. if (!dec_ctx) return AVERROR(ENOMEM);
  102. avcodec_parameters_to_context(dec_ctx,
  103. fmt_ctx->streams[audio_stream_index]->codecpar);
  104. /* init the audio decoder */
  105. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  106. av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
  107. return ret;
  108. }
  109. return 0;
  110. }
  111. static int32_t FFmpegInitFilters(const char *filters_descr) {
  112. char args[512];
  113. int32_t ret = 0;
  114. const AVFilter *abuffersrc = avfilter_get_by_name("abuffer");
  115. const AVFilter *abuffersink = avfilter_get_by_name("abuffersink");
  116. AVFilterInOut *outputs = avfilter_inout_alloc();
  117. AVFilterInOut *inputs = avfilter_inout_alloc();
  118. static const enum AVSampleFormat out_sample_fmts[] = {AV_SAMPLE_FMT_S16,
  119. AV_SAMPLE_FMT_NONE};
  120. static const int32_t out_sample_rates[] = {16000, -1};
  121. const AVFilterLink *outlink;
  122. AVRational time_base = fmt_ctx->streams[audio_stream_index]->time_base;
  123. filter_graph = avfilter_graph_alloc();
  124. if (!outputs || !inputs || !filter_graph) {
  125. ret = AVERROR(ENOMEM);
  126. goto end;
  127. }
  128. /* buffer audio source: the decoded frames from the decoder will be inserted
  129. * here. */
  130. if (dec_ctx->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
  131. av_channel_layout_default(&dec_ctx->ch_layout,
  132. dec_ctx->ch_layout.nb_channels);
  133. ret = snprintf(args, sizeof(args),
  134. "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=",
  135. time_base.num, time_base.den, dec_ctx->sample_rate,
  136. av_get_sample_fmt_name(dec_ctx->sample_fmt));
  137. av_channel_layout_describe(&dec_ctx->ch_layout, args + ret,
  138. sizeof(args) - ret);
  139. ret = avfilter_graph_create_filter(&buffersrc_ctx, abuffersrc, "in", args,
  140. NULL, filter_graph);
  141. if (ret < 0) {
  142. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
  143. goto end;
  144. }
  145. /* buffer audio sink: to terminate the filter chain. */
  146. ret = avfilter_graph_create_filter(&buffersink_ctx, abuffersink, "out", NULL,
  147. NULL, filter_graph);
  148. if (ret < 0) {
  149. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
  150. goto end;
  151. }
  152. ret = av_opt_set_int_list(buffersink_ctx, "sample_fmts", out_sample_fmts, -1,
  153. AV_OPT_SEARCH_CHILDREN);
  154. if (ret < 0) {
  155. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
  156. goto end;
  157. }
  158. ret =
  159. av_opt_set(buffersink_ctx, "ch_layouts", "mono", AV_OPT_SEARCH_CHILDREN);
  160. if (ret < 0) {
  161. av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
  162. goto end;
  163. }
  164. ret = av_opt_set_int_list(buffersink_ctx, "sample_rates", out_sample_rates,
  165. -1, AV_OPT_SEARCH_CHILDREN);
  166. if (ret < 0) {
  167. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
  168. goto end;
  169. }
  170. /*
  171. * Set the endpoints for the filter graph. The filter_graph will
  172. * be linked to the graph described by filters_descr.
  173. */
  174. /*
  175. * The buffer source output must be connected to the input pad of
  176. * the first filter described by filters_descr; since the first
  177. * filter input label is not specified, it is set to "in" by
  178. * default.
  179. */
  180. outputs->name = av_strdup("in");
  181. outputs->filter_ctx = buffersrc_ctx;
  182. outputs->pad_idx = 0;
  183. outputs->next = NULL;
  184. /*
  185. * The buffer sink input must be connected to the output pad of
  186. * the last filter described by filters_descr; since the last
  187. * filter output label is not specified, it is set to "out" by
  188. * default.
  189. */
  190. inputs->name = av_strdup("out");
  191. inputs->filter_ctx = buffersink_ctx;
  192. inputs->pad_idx = 0;
  193. inputs->next = NULL;
  194. if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr, &inputs,
  195. &outputs, NULL)) < 0)
  196. goto end;
  197. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0) goto end;
  198. /* Print summary of the sink buffer
  199. * Note: args buffer is reused to store channel layout string */
  200. outlink = buffersink_ctx->inputs[0];
  201. av_channel_layout_describe(&outlink->ch_layout, args, sizeof(args));
  202. fprintf(
  203. stdout,
  204. "Event:FFmpeg: Detect audio stream ok, srate:%dHz fmt:%s chlayout:%s\n",
  205. (int)outlink->sample_rate,
  206. (char *)av_x_if_null(
  207. av_get_sample_fmt_name((AVSampleFormat)outlink->format), "?"),
  208. args);
  209. fflush(stdout);
  210. end:
  211. avfilter_inout_free(&inputs);
  212. avfilter_inout_free(&outputs);
  213. return ret;
  214. }
  215. static void FFmpegDecodeFrame(const AVFrame *frame,
  216. const sherpa_ncnn::Recognizer &recognizer,
  217. sherpa_ncnn::Stream *s,
  218. sherpa_ncnn::Display *display,
  219. std::string *last_text, int32_t *segment_index,
  220. int32_t *zero_samples) {
  221. // TODO: FIXME: Can we directly consume frame by s without buffer?
  222. #define N 3200 // 0.2 s. Sample rate is fixed to 16 kHz
  223. static float samples[N];
  224. static int32_t nb_samples = 0;
  225. const int16_t *p = (int16_t *)frame->data[0];
  226. if (frame->nb_samples + nb_samples >= N) {
  227. s->AcceptWaveform(16000, samples, nb_samples);
  228. while (recognizer.IsReady(s)) {
  229. recognizer.DecodeStream(s);
  230. }
  231. bool is_endpoint = recognizer.IsEndpoint(s);
  232. auto text = recognizer.GetResult(s).text;
  233. if (!text.empty() && *last_text != text) {
  234. *last_text = text;
  235. std::transform(text.begin(), text.end(), text.begin(),
  236. [](auto c) { return std::tolower(c); });
  237. display->Print(*segment_index, text);
  238. }
  239. if (is_endpoint) {
  240. if (!text.empty()) {
  241. (*segment_index)++;
  242. }
  243. recognizer.Reset(s);
  244. }
  245. nb_samples = 0;
  246. }
  247. for (int32_t i = 0; i < frame->nb_samples; i++) {
  248. if (p[i] == 0) {
  249. (*zero_samples)++;
  250. }
  251. samples[nb_samples++] = p[i] / 32768.;
  252. }
  253. }
  254. static inline char *FFmpegAvError2String(int32_t errnum) {
  255. static char str[AV_ERROR_MAX_STRING_SIZE];
  256. memset(str, 0, sizeof(str));
  257. return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
  258. }
  259. // When stream unpublish, use this signal to notify application.
  260. static int32_t signal_unpublish_sigusr1 = 0;
  261. static void Handler(int32_t sig) {
  262. if (sig == SIGUSR1) {
  263. fprintf(stdout, "\nEvent:Signal: Got signal %d\n", sig);
  264. fflush(stdout);
  265. signal_unpublish_sigusr1 = 1;
  266. return;
  267. }
  268. fprintf(stdout, "\nEvent:Signal: Caught Ctrl + C. Exiting...\n");
  269. fflush(stdout);
  270. signal(sig, SIG_DFL);
  271. raise(sig);
  272. };
  273. #define SET_STRING_BY_ENV(config, key) \
  274. if (getenv(key)) { \
  275. config = getenv(key); \
  276. }
  277. #define SET_CONFIG_BY_ENV(config, key, required) \
  278. config = ""; \
  279. SET_STRING_BY_ENV(config, key); \
  280. if (!(config).empty() && required) { \
  281. parsed_required_envs++; \
  282. }
  283. #define SET_INTEGER_BY_ENV(config, key) \
  284. { \
  285. std::string val; \
  286. SET_STRING_BY_ENV(val, "SHERPA_NCNN_ASD_ENDPOINTS"); \
  287. if (!val.empty() && ::atoi(val.c_str()) > 0) { \
  288. config = ::atoi(val.c_str()); \
  289. } \
  290. }
  291. static int32_t ParseConfigFromENV(sherpa_ncnn::RecognizerConfig *config,
  292. std::string *input_url) {
  293. int32_t parsed_required_envs = 0;
  294. sherpa_ncnn::ModelConfig &mc = config->model_config;
  295. SET_CONFIG_BY_ENV(mc.tokens, "SHERPA_NCNN_TOKENS", true);
  296. SET_CONFIG_BY_ENV(mc.encoder_param, "SHERPA_NCNN_ENCODER_PARAM", true);
  297. SET_CONFIG_BY_ENV(mc.encoder_bin, "SHERPA_NCNN_ENCODER_BIN", true);
  298. SET_CONFIG_BY_ENV(mc.decoder_param, "SHERPA_NCNN_DECODER_PARAM", true);
  299. SET_CONFIG_BY_ENV(mc.decoder_bin, "SHERPA_NCNN_DECODER_BIN", true);
  300. SET_CONFIG_BY_ENV(mc.joiner_param, "SHERPA_NCNN_JOINER_PARAM", true);
  301. SET_CONFIG_BY_ENV(mc.joiner_bin, "SHERPA_NCNN_JOINER_BIN", true);
  302. SET_CONFIG_BY_ENV(*input_url, "SHERPA_NCNN_INPUT_URL", true);
  303. std::string val;
  304. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_NUM_THREADS", false);
  305. if (!val.empty()) {
  306. if (atoi(val.c_str()) <= 0) {
  307. fprintf(stderr, "Invalid SHERPA_NCNN_NUM_THREADS=%s\n", val.c_str());
  308. return -1;
  309. }
  310. mc.encoder_opt.num_threads = atoi(val.c_str());
  311. mc.decoder_opt.num_threads = atoi(val.c_str());
  312. mc.joiner_opt.num_threads = atoi(val.c_str());
  313. }
  314. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_METHOD", false);
  315. if (!val.empty()) {
  316. if (val != "greedy_search" && val != "modified_beam_search") {
  317. fprintf(stderr, "Invalid SHERPA_NCNN_METHOD=%s\n", val.c_str());
  318. return -1;
  319. }
  320. config->decoder_config.method = val;
  321. }
  322. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_ENABLE_ENDPOINT", false);
  323. if (!val.empty()) {
  324. std::transform(val.begin(), val.end(), val.begin(),
  325. [](auto c) { return std::tolower(c); });
  326. config->enable_endpoint = val == "true" || val == "on";
  327. }
  328. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_RULE1_MIN_TRAILING_SILENCE", false);
  329. if (!val.empty()) {
  330. if (::atof(val.c_str()) <= 0) {
  331. fprintf(stderr, "Invalid SHERPA_NCNN_RULE1_MIN_TRAILING_SILENCE=%s\n",
  332. val.c_str());
  333. return -1;
  334. }
  335. config->endpoint_config.rule1.min_trailing_silence = ::atof(val.c_str());
  336. }
  337. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_RULE2_MIN_TRAILING_SILENCE", false);
  338. if (!val.empty()) {
  339. if (::atof(val.c_str()) <= 0) {
  340. fprintf(stderr, "Invalid SHERPA_NCNN_RULE2_MIN_TRAILING_SILENCE=%s\n",
  341. val.c_str());
  342. return -1;
  343. }
  344. config->endpoint_config.rule2.min_trailing_silence = ::atof(val.c_str());
  345. }
  346. SET_CONFIG_BY_ENV(val, "SHERPA_NCNN_RULE3_MIN_UTTERANCE_LENGTH", false);
  347. if (!val.empty()) {
  348. if (::atof(val.c_str()) <= 0) {
  349. fprintf(stderr, "Invalid SHERPA_NCNN_RULE3_MIN_UTTERANCE_LENGTH=%s\n",
  350. val.c_str());
  351. return -1;
  352. }
  353. config->endpoint_config.rule3.min_utterance_length = ::atof(val.c_str());
  354. }
  355. return parsed_required_envs;
  356. }
  357. static void SetDefaultConfigurations(sherpa_ncnn::RecognizerConfig *config) {
  358. int32_t num_threads = 4;
  359. config->model_config.encoder_opt.num_threads = num_threads;
  360. config->model_config.decoder_opt.num_threads = num_threads;
  361. config->model_config.joiner_opt.num_threads = num_threads;
  362. config->enable_endpoint = true;
  363. config->endpoint_config.rule1.min_trailing_silence = 2.4;
  364. config->endpoint_config.rule2.min_trailing_silence = 1.2;
  365. config->endpoint_config.rule3.min_utterance_length = 300;
  366. const float expected_sampling_rate = 16000;
  367. config->feat_config.sampling_rate = expected_sampling_rate;
  368. config->feat_config.feature_dim = 80;
  369. }
  370. static int32_t OverwriteConfigByCLI(int32_t argc, char **argv,
  371. sherpa_ncnn::RecognizerConfig *config,
  372. std::string *input_url) {
  373. if (argc > 1) config->model_config.tokens = argv[1];
  374. if (argc > 2) config->model_config.encoder_param = argv[2];
  375. if (argc > 3) config->model_config.encoder_bin = argv[3];
  376. if (argc > 4) config->model_config.decoder_param = argv[4];
  377. if (argc > 5) config->model_config.decoder_bin = argv[5];
  378. if (argc > 6) config->model_config.joiner_param = argv[6];
  379. if (argc > 7) config->model_config.joiner_bin = argv[7];
  380. if (argc > 8) *input_url = argv[8];
  381. if (argc >= 10 && atoi(argv[9]) > 0) {
  382. int32_t num_threads = atoi(argv[9]);
  383. config->model_config.encoder_opt.num_threads = num_threads;
  384. config->model_config.decoder_opt.num_threads = num_threads;
  385. config->model_config.joiner_opt.num_threads = num_threads;
  386. }
  387. if (argc == 11) {
  388. std::string val = argv[10];
  389. if (val != "greedy_search" && val != "modified_beam_search") {
  390. fprintf(stderr, "Invalid SHERPA_NCNN_METHOD=%s\n", val.c_str());
  391. return -1;
  392. }
  393. config->decoder_config.method = val;
  394. }
  395. return 0;
  396. }
  397. // A simple display, without window support, doesn't rewrite current line.
  398. // It only output the new text, which only works in greedy_search mode.
  399. // It doesn't support modified_beam_search mode, which might change the
  400. // generated text.
  401. class SimpleDisplay : public sherpa_ncnn::Display {
  402. public:
  403. SimpleDisplay(std::string label) {
  404. label_ = label.empty() ? "" : label + ":";
  405. }
  406. void Print(int32_t segment_id, const std::string &s) {
  407. if (last_segment_ != segment_id) {
  408. last_segment_ = segment_id;
  409. last_text_ = "";
  410. if (segment_id) {
  411. fprintf(stderr, "\n");
  412. }
  413. fprintf(stderr, "%s%d:", label_.c_str(), segment_id);
  414. if (!s.empty() && s.at(0) != ' ') {
  415. fprintf(stderr, " ");
  416. }
  417. }
  418. if (s.length() > last_text_.length()) {
  419. std::string tmp(s.begin() + last_text_.length(), s.end());
  420. fprintf(stderr, "%s", tmp.c_str());
  421. } else {
  422. fprintf(stderr, "%s", s.c_str());
  423. }
  424. last_text_ = s;
  425. }
  426. private:
  427. std::string label_;
  428. std::string last_text_;
  429. int32_t last_segment_ = -1;
  430. };
  431. std::unique_ptr<sherpa_ncnn::Display> CreateDisplay() {
  432. std::string val;
  433. SET_STRING_BY_ENV(val, "SHERPA_NCNN_SIMPLE_DISLAY");
  434. std::transform(val.begin(), val.end(), val.begin(),
  435. [](auto c) { return std::tolower(c); });
  436. if (val == "on" || val == "true") {
  437. std::string label;
  438. SET_STRING_BY_ENV(label, "SHERPA_NCNN_DISPLAY_LABEL");
  439. return std::make_unique<SimpleDisplay>(label);
  440. } else {
  441. return std::make_unique<sherpa_ncnn::Display>();
  442. }
  443. }
  444. int32_t main(int32_t argc, char **argv) {
  445. // Set the default values for config.
  446. sherpa_ncnn::RecognizerConfig config;
  447. SetDefaultConfigurations(&config);
  448. // Load and overwrite config from environment variables.
  449. std::string input_url;
  450. int32_t parsed_required_envs = ParseConfigFromENV(&config, &input_url);
  451. if (parsed_required_envs < 0) {
  452. exit(-1);
  453. }
  454. // Error if not set by neither environment variables nor CLI.
  455. if (parsed_required_envs < 8 && (argc < 9 || argc > 11)) {
  456. const char *usage = R"usage(
  457. Usage:
  458. ./bin/sherpa-ncnn-ffmpeg \
  459. /path/to/tokens.txt \
  460. /path/to/encoder.ncnn.param \
  461. /path/to/encoder.ncnn.bin \
  462. /path/to/decoder.ncnn.param \
  463. /path/to/decoder.ncnn.bin \
  464. /path/to/joiner.ncnn.param \
  465. /path/to/joiner.ncnn.bin \
  466. ffmpeg-input-url \
  467. [num_threads] [decode_method, can be greedy_search/modified_beam_search]
  468. Or configure by environment variables:
  469. SHERPA_NCNN_TOKENS=/path/to/tokens.txt \
  470. SHERPA_NCNN_ENCODER_PARAM=/path/to/encoder_jit_trace-pnnx.ncnn.param \
  471. SHERPA_NCNN_ENCODER_BIN=/path/to/encoder_jit_trace-pnnx.ncnn.bin \
  472. SHERPA_NCNN_DECODER_PARAM=/path/to/decoder_jit_trace-pnnx.ncnn.param \
  473. SHERPA_NCNN_DECODER_BIN=/path/to/decoder_jit_trace-pnnx.ncnn.bin \
  474. SHERPA_NCNN_JOINER_PARAM=/path/to/joiner_jit_trace-pnnx.ncnn.param \
  475. SHERPA_NCNN_JOINER_BIN=/path/to/joiner_jit_trace-pnnx.ncnn.bin \
  476. SHERPA_NCNN_INPUT_URL=ffmpeg-input-url \
  477. SHERPA_NCNN_NUM_THREADS=4 \
  478. SHERPA_NCNN_METHOD=greedy_search|modified_beam_search \
  479. SHERPA_NCNN_ENABLE_ENDPOINT=on|off \
  480. SHERPA_NCNN_RULE1_MIN_TRAILING_SILENCE=2.4 \
  481. SHERPA_NCNN_RULE2_MIN_TRAILING_SILENCE=1.2 \
  482. SHERPA_NCNN_RULE3_MIN_UTTERANCE_LENGTH=300 \
  483. SHERPA_NCNN_SIMPLE_DISLAY=on|off \
  484. SHERPA_NCNN_DISPLAY_LABEL=Data \
  485. SHERPA_NCNN_ASD_ENDPOINTS=3 \
  486. SHERPA_NCNN_ASD_SAMPLES=10 \
  487. ./bin/sherpa-ncnn-ffmpeg
  488. Please refer to
  489. https://k2-fsa.github.io/sherpa/ncnn/pretrained_models/index.html
  490. for a list of pre-trained models to download.
  491. )usage";
  492. fprintf(stderr, "%s\n", usage);
  493. fprintf(stderr, "argc, %d\n", argc);
  494. return -1;
  495. }
  496. signal(SIGINT, Handler);
  497. signal(SIGUSR1, Handler);
  498. // Overwrite the config by CLI.
  499. if (OverwriteConfigByCLI(argc, argv, &config, &input_url)) {
  500. exit(-1);
  501. }
  502. fprintf(stdout, "Event:K2: Config is %s\n", config.ToString().c_str());
  503. fflush(stdout);
  504. sherpa_ncnn::Recognizer recognizer(config);
  505. auto s = recognizer.CreateStream();
  506. fprintf(stdout, "Event:K2: Create recognizer ok\n");
  507. fflush(stdout);
  508. // Initialize FFmpeg framework.
  509. AVPacket *packet = av_packet_alloc();
  510. AVFrame *frame = av_frame_alloc();
  511. AVFrame *filt_frame = av_frame_alloc();
  512. if (!packet || !frame || !filt_frame) {
  513. fprintf(stderr, "Could not allocate frame or packet\n");
  514. exit(1);
  515. }
  516. int32_t ret;
  517. fprintf(stdout, "Event:FFmpeg: Open input %s\n", input_url.c_str());
  518. fflush(stdout);
  519. if ((ret = FFmpegOpenInputFile(input_url.c_str())) < 0) {
  520. fprintf(stderr, "Open input file %s failed, r0=%d\n", input_url.c_str(),
  521. ret);
  522. exit(1);
  523. }
  524. fprintf(stdout, "Event:FFmpeg: Open input ok, %s\n", input_url.c_str());
  525. fflush(stdout);
  526. if ((ret = FFmpegInitFilters(filter_descr)) < 0) {
  527. fprintf(stderr, "Init filters %s failed, r0=%d\n", filter_descr, ret);
  528. exit(1);
  529. }
  530. int32_t asd_endpoints = 0, asd_samples = 0;
  531. SET_INTEGER_BY_ENV(asd_endpoints, "SHERPA_NCNN_ASD_ENDPOINTS");
  532. SET_INTEGER_BY_ENV(asd_samples, "SHERPA_NCNN_ASD_SAMPLES");
  533. std::string last_text;
  534. int32_t segment_index = 0, zero_samples = 0, asd_segment = 0;
  535. std::unique_ptr<sherpa_ncnn::Display> display = CreateDisplay();
  536. while (1) {
  537. if ((ret = av_read_frame(fmt_ctx, packet)) < 0) {
  538. break;
  539. }
  540. // Reset the ASD segment when stream unpublish.
  541. if (signal_unpublish_sigusr1) {
  542. signal_unpublish_sigusr1 = 0;
  543. if (asd_segment != segment_index) {
  544. asd_segment = segment_index;
  545. }
  546. }
  547. // ASD(Active speaker detection), note that 16000 samples is 1s.
  548. if (asd_samples && zero_samples > asd_samples * 16000) {
  549. // When unpublish, there might be some left samples in buffer.
  550. if (asd_endpoints && segment_index - asd_segment < asd_endpoints) {
  551. fprintf(stdout,
  552. "\nEvent:FFmpeg: All silence samples, incorrect microphone?\n");
  553. fflush(stdout);
  554. }
  555. zero_samples = 0;
  556. }
  557. if (packet->stream_index == audio_stream_index) {
  558. ret = avcodec_send_packet(dec_ctx, packet);
  559. if (ret < 0) {
  560. av_log(NULL, AV_LOG_ERROR,
  561. "Error while sending a packet to the decoder\n");
  562. break;
  563. }
  564. while (ret >= 0) {
  565. ret = avcodec_receive_frame(dec_ctx, frame);
  566. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  567. break;
  568. } else if (ret < 0) {
  569. av_log(NULL, AV_LOG_ERROR,
  570. "Error while receiving a frame from the decoder\n");
  571. exit(1);
  572. }
  573. if (ret >= 0) {
  574. /* push the audio data from decoded frame into the filtergraph */
  575. if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame,
  576. AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
  577. av_log(NULL, AV_LOG_ERROR,
  578. "Error while feeding the audio filtergraph\n");
  579. break;
  580. }
  581. /* pull filtered audio from the filtergraph */
  582. while (1) {
  583. ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
  584. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  585. break;
  586. }
  587. if (ret < 0) {
  588. fprintf(stderr, "Error get frame, ret=%d\n", ret);
  589. exit(1);
  590. }
  591. FFmpegDecodeFrame(filt_frame, recognizer, s.get(), display.get(),
  592. &last_text, &segment_index, &zero_samples);
  593. av_frame_unref(filt_frame);
  594. }
  595. av_frame_unref(frame);
  596. }
  597. }
  598. }
  599. av_packet_unref(packet);
  600. }
  601. // Add some tail padding
  602. float tail_paddings[4800] = {0}; // 0.3 seconds at 16 kHz sample rate
  603. s->AcceptWaveform(16000, tail_paddings, 4800);
  604. s->InputFinished();
  605. while (recognizer.IsReady(s.get())) {
  606. recognizer.DecodeStream(s.get());
  607. }
  608. auto text = recognizer.GetResult(s.get()).text;
  609. if (!text.empty() && last_text != text) {
  610. last_text = text;
  611. std::transform(text.begin(), text.end(), text.begin(),
  612. [](auto c) { return std::tolower(c); });
  613. display->Print(segment_index, text);
  614. }
  615. avfilter_graph_free(&filter_graph);
  616. avcodec_free_context(&dec_ctx);
  617. avformat_close_input(&fmt_ctx);
  618. av_packet_free(&packet);
  619. av_frame_free(&frame);
  620. av_frame_free(&filt_frame);
  621. if (ret < 0 && ret != AVERROR_EOF) {
  622. fprintf(stderr, "Error occurred: %s\n", FFmpegAvError2String(ret));
  623. exit(1);
  624. }
  625. return 0;
  626. }