sherpa-ncnn-ffmpeg.cc 24 KB

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