sherpa-ncnn-ffmpeg.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include "sherpa-ncnn/c-api/c-api.h"
  22. /*
  23. * Copyright (c) 2010 Nicolas George
  24. * Copyright (c) 2011 Stefano Sabatini
  25. * Copyright (c) 2012 Clément Bœsch
  26. *
  27. * Permission is hereby granted, free of charge, to any person obtaining a copy
  28. * of this software and associated documentation files (the "Software"), to deal
  29. * in the Software without restriction, including without limitation the rights
  30. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  31. * copies of the Software, and to permit persons to whom the Software is
  32. * furnished to do so, subject to the following conditions:
  33. *
  34. * The above copyright notice and this permission notice shall be included in
  35. * all copies or substantial portions of the Software.
  36. *
  37. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  39. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  40. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  42. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  43. * THE SOFTWARE.
  44. */
  45. /**
  46. * @file audio decoding and filtering usage example
  47. * @example sherpa-ncnn-ffmpeg.c
  48. *
  49. * Demux, decode and filter audio input file, generate a raw audio
  50. * file to be played with ffplay.
  51. */
  52. #include <unistd.h>
  53. #ifdef __cplusplus
  54. extern "C" {
  55. #endif
  56. #include <libavutil/samplefmt.h>
  57. #include <libavcodec/avcodec.h>
  58. #include <libavformat/avformat.h>
  59. #include <libavfilter/buffersink.h>
  60. #include <libavfilter/buffersrc.h>
  61. #include <libavutil/channel_layout.h>
  62. #include <libavutil/opt.h>
  63. #ifdef __cplusplus
  64. }
  65. #endif
  66. static const char *filter_descr = "aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono";
  67. static AVFormatContext *fmt_ctx;
  68. static AVCodecContext *dec_ctx;
  69. AVFilterContext *buffersink_ctx;
  70. AVFilterContext *buffersrc_ctx;
  71. AVFilterGraph *filter_graph;
  72. static int audio_stream_index = -1;
  73. static int open_input_file(const char *filename)
  74. {
  75. const AVCodec *dec;
  76. int ret;
  77. if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
  78. av_log(NULL, AV_LOG_ERROR, "Cannot open input file %s\n", filename);
  79. return ret;
  80. }
  81. if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  82. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  83. return ret;
  84. }
  85. /* select the audio stream */
  86. ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
  87. if (ret < 0) {
  88. av_log(NULL, AV_LOG_ERROR, "Cannot find an audio stream in the input file\n");
  89. return ret;
  90. }
  91. audio_stream_index = ret;
  92. /* create decoding context */
  93. dec_ctx = avcodec_alloc_context3(dec);
  94. if (!dec_ctx)
  95. return AVERROR(ENOMEM);
  96. avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[audio_stream_index]->codecpar);
  97. /* init the audio decoder */
  98. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  99. av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
  100. return ret;
  101. }
  102. return 0;
  103. }
  104. static int init_filters(const char *filters_descr)
  105. {
  106. char args[512];
  107. int ret = 0;
  108. const AVFilter *abuffersrc = avfilter_get_by_name("abuffer");
  109. const AVFilter *abuffersink = avfilter_get_by_name("abuffersink");
  110. AVFilterInOut *outputs = avfilter_inout_alloc();
  111. AVFilterInOut *inputs = avfilter_inout_alloc();
  112. static const enum AVSampleFormat out_sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE };
  113. static const int out_sample_rates[] = { 16000, -1 };
  114. const AVFilterLink *outlink;
  115. AVRational time_base = fmt_ctx->streams[audio_stream_index]->time_base;
  116. filter_graph = avfilter_graph_alloc();
  117. if (!outputs || !inputs || !filter_graph) {
  118. ret = AVERROR(ENOMEM);
  119. goto end;
  120. }
  121. /* buffer audio source: the decoded frames from the decoder will be inserted here. */
  122. if (dec_ctx->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
  123. av_channel_layout_default(&dec_ctx->ch_layout, dec_ctx->ch_layout.nb_channels);
  124. ret = snprintf(args, sizeof(args),
  125. "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=",
  126. time_base.num, time_base.den, dec_ctx->sample_rate,
  127. av_get_sample_fmt_name(dec_ctx->sample_fmt));
  128. av_channel_layout_describe(&dec_ctx->ch_layout, args + ret, sizeof(args) - ret);
  129. ret = avfilter_graph_create_filter(&buffersrc_ctx, abuffersrc, "in",
  130. args, NULL, filter_graph);
  131. if (ret < 0) {
  132. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
  133. goto end;
  134. }
  135. /* buffer audio sink: to terminate the filter chain. */
  136. ret = avfilter_graph_create_filter(&buffersink_ctx, abuffersink, "out",
  137. NULL, NULL, filter_graph);
  138. if (ret < 0) {
  139. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
  140. goto end;
  141. }
  142. ret = av_opt_set_int_list(buffersink_ctx, "sample_fmts", out_sample_fmts, -1,
  143. AV_OPT_SEARCH_CHILDREN);
  144. if (ret < 0) {
  145. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
  146. goto end;
  147. }
  148. ret = av_opt_set(buffersink_ctx, "ch_layouts", "mono",
  149. AV_OPT_SEARCH_CHILDREN);
  150. if (ret < 0) {
  151. av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
  152. goto end;
  153. }
  154. ret = av_opt_set_int_list(buffersink_ctx, "sample_rates", out_sample_rates, -1,
  155. AV_OPT_SEARCH_CHILDREN);
  156. if (ret < 0) {
  157. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
  158. goto end;
  159. }
  160. /*
  161. * Set the endpoints for the filter graph. The filter_graph will
  162. * be linked to the graph described by filters_descr.
  163. */
  164. /*
  165. * The buffer source output must be connected to the input pad of
  166. * the first filter described by filters_descr; since the first
  167. * filter input label is not specified, it is set to "in" by
  168. * default.
  169. */
  170. outputs->name = av_strdup("in");
  171. outputs->filter_ctx = buffersrc_ctx;
  172. outputs->pad_idx = 0;
  173. outputs->next = NULL;
  174. /*
  175. * The buffer sink input must be connected to the output pad of
  176. * the last filter described by filters_descr; since the last
  177. * filter output label is not specified, it is set to "out" by
  178. * default.
  179. */
  180. inputs->name = av_strdup("out");
  181. inputs->filter_ctx = buffersink_ctx;
  182. inputs->pad_idx = 0;
  183. inputs->next = NULL;
  184. if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
  185. &inputs, &outputs, NULL)) < 0)
  186. goto end;
  187. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
  188. goto end;
  189. /* Print summary of the sink buffer
  190. * Note: args buffer is reused to store channel layout string */
  191. outlink = buffersink_ctx->inputs[0];
  192. av_channel_layout_describe(&outlink->ch_layout, args, sizeof(args));
  193. av_log(NULL, AV_LOG_INFO, "Output: srate:%dHz fmt:%s chlayout:%s\n",
  194. (int)outlink->sample_rate,
  195. (char *)av_x_if_null(av_get_sample_fmt_name((AVSampleFormat)outlink->format), "?"),
  196. args);
  197. end:
  198. avfilter_inout_free(&inputs);
  199. avfilter_inout_free(&outputs);
  200. return ret;
  201. }
  202. static void sherpa_decode_frame(const AVFrame *frame, SherpaNcnnRecognizer *recognizer, SherpaNcnnStream *s, SherpaNcnnDisplay * display, int *segment_id)
  203. {
  204. #define N 3200 // 0.2 s. Sample rate is fixed to 16 kHz
  205. static float samples[N];
  206. static int nb_samples = 0;
  207. const int16_t *p = (int16_t*)frame->data[0];
  208. if (frame->nb_samples + nb_samples >= N) {
  209. AcceptWaveform(s, 16000, samples, nb_samples);
  210. while (IsReady(recognizer, s)) {
  211. Decode(recognizer, s);
  212. }
  213. SherpaNcnnResult *r = GetResult(recognizer, s);
  214. if (strlen(r->text)) {
  215. SherpaNcnnPrint(display, *segment_id, r->text);
  216. }
  217. if (IsEndpoint(recognizer, s)) {
  218. Reset(recognizer, s);
  219. if (strlen(r->text)) {
  220. ++(*segment_id);
  221. }
  222. }
  223. DestroyResult(r);
  224. nb_samples = 0;
  225. }
  226. for (int i = 0; i < frame->nb_samples; i++) {
  227. samples[nb_samples++] = p[i] / 32768.;
  228. }
  229. }
  230. static inline char *__av_err2str(int errnum)
  231. {
  232. static char str[AV_ERROR_MAX_STRING_SIZE];
  233. memset(str, 0, sizeof(str));
  234. return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
  235. }
  236. int main(int argc, char **argv)
  237. {
  238. int ret;
  239. int num_threads = 4;
  240. AVPacket *packet = av_packet_alloc();
  241. AVFrame *frame = av_frame_alloc();
  242. AVFrame *filt_frame = av_frame_alloc();
  243. const char *kUsage =
  244. "\n"
  245. "Usage:\n"
  246. " ./sherpa-ncnn-ffmpeg \\\n"
  247. " /path/to/tokens.txt \\\n"
  248. " /path/to/encoder.ncnn.param \\\n"
  249. " /path/to/encoder.ncnn.bin \\\n"
  250. " /path/to/decoder.ncnn.param \\\n"
  251. " /path/to/decoder.ncnn.bin \\\n"
  252. " /path/to/joiner.ncnn.param \\\n"
  253. " /path/to/joiner.ncnn.bin \\\n"
  254. " /path/to/foo.wav [<num_threads> [decode_method, can be "
  255. "greedy_search/modified_beam_search]]"
  256. "\n\n"
  257. "Please refer to \n"
  258. "https://k2-fsa.github.io/sherpa/ncnn/pretrained_models/index.html\n"
  259. "for a list of pre-trained models to download.\n";
  260. if (!packet || !frame || !filt_frame) {
  261. fprintf(stderr, "Could not allocate frame or packet\n");
  262. exit(1);
  263. }
  264. if (argc < 9 || argc > 11) {
  265. fprintf(stderr, "%s\n", kUsage);
  266. return -1;
  267. }
  268. SherpaNcnnRecognizerConfig config;
  269. config.model_config.tokens = argv[1];
  270. config.model_config.encoder_param = argv[2];
  271. config.model_config.encoder_bin = argv[3];
  272. config.model_config.decoder_param = argv[4];
  273. config.model_config.decoder_bin = argv[5];
  274. config.model_config.joiner_param = argv[6];
  275. config.model_config.joiner_bin = argv[7];
  276. if (argc >= 10 && atoi(argv[9]) > 0) {
  277. num_threads = atoi(argv[9]);
  278. }
  279. config.model_config.num_threads = num_threads;
  280. config.model_config.use_vulkan_compute = 0;
  281. config.decoder_config.decoding_method = "greedy_search";
  282. if (argc == 11) {
  283. config.decoder_config.decoding_method = argv[10];
  284. }
  285. config.decoder_config.num_active_paths = 4;
  286. config.enable_endpoint = 1;
  287. config.rule1_min_trailing_silence = 2.4;
  288. config.rule2_min_trailing_silence = 1.2;
  289. config.rule3_min_utterance_length = 300;
  290. config.feat_config.sampling_rate = 16000;
  291. config.feat_config.feature_dim = 80;
  292. SherpaNcnnRecognizer *recognizer = CreateRecognizer(&config);
  293. SherpaNcnnStream *s = CreateStream(recognizer);
  294. SherpaNcnnDisplay *display = CreateDisplay(60);
  295. int segment_id = 0;
  296. if ((ret = open_input_file(argv[8])) < 0)
  297. exit(1);
  298. if ((ret = init_filters(filter_descr)) < 0)
  299. exit(1);
  300. /* read all packets */
  301. while (1) {
  302. if ((ret = av_read_frame(fmt_ctx, packet)) < 0)
  303. break;
  304. if (packet->stream_index == audio_stream_index) {
  305. ret = avcodec_send_packet(dec_ctx, packet);
  306. if (ret < 0) {
  307. av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
  308. break;
  309. }
  310. while (ret >= 0) {
  311. ret = avcodec_receive_frame(dec_ctx, frame);
  312. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  313. break;
  314. } else if (ret < 0) {
  315. av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
  316. exit(1);
  317. }
  318. if (ret >= 0) {
  319. /* push the audio data from decoded frame into the filtergraph */
  320. if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
  321. av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
  322. break;
  323. }
  324. /* pull filtered audio from the filtergraph */
  325. while (1) {
  326. ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
  327. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  328. break;
  329. if (ret < 0)
  330. exit(1);
  331. sherpa_decode_frame(filt_frame, recognizer, s, display, &segment_id);
  332. av_frame_unref(filt_frame);
  333. }
  334. av_frame_unref(frame);
  335. }
  336. }
  337. }
  338. av_packet_unref(packet);
  339. }
  340. // add some tail padding
  341. float tail_paddings[4800] = {0}; // 0.3 seconds at 16 kHz sample rate
  342. AcceptWaveform(s, 16000, tail_paddings, 4800);
  343. InputFinished(s);
  344. while (IsReady(recognizer, s)) {
  345. Decode(recognizer, s);
  346. }
  347. SherpaNcnnResult *r = GetResult(recognizer, s);
  348. if(strlen(r->text)) {
  349. SherpaNcnnPrint(display, segment_id, r->text);
  350. }
  351. DestroyResult(r);
  352. DestroyDisplay(display);
  353. DestroyStream(s);
  354. DestroyRecognizer(recognizer);
  355. avfilter_graph_free(&filter_graph);
  356. avcodec_free_context(&dec_ctx);
  357. avformat_close_input(&fmt_ctx);
  358. av_packet_free(&packet);
  359. av_frame_free(&frame);
  360. av_frame_free(&filt_frame);
  361. if (ret < 0 && ret != AVERROR_EOF) {
  362. fprintf(stderr, "Error occurred: %s\n", __av_err2str(ret));
  363. exit(1);
  364. }
  365. fprintf(stderr, "\n");
  366. return 0;
  367. }