sherpa-ncnn-ffmpeg.cc 28 KB

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