sherpa-ncnn-ffmpeg.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. extern "C" {
  54. #include <libavcodec/avcodec.h>
  55. #include <libavformat/avformat.h>
  56. #include <libavfilter/buffersink.h>
  57. #include <libavfilter/buffersrc.h>
  58. #include <libavutil/channel_layout.h>
  59. #include <libavutil/opt.h>
  60. }
  61. static const char *filter_descr = "aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono";
  62. static AVFormatContext *fmt_ctx;
  63. static AVCodecContext *dec_ctx;
  64. AVFilterContext *buffersink_ctx;
  65. AVFilterContext *buffersrc_ctx;
  66. AVFilterGraph *filter_graph;
  67. static int audio_stream_index = -1;
  68. static int open_input_file(const char *filename)
  69. {
  70. const AVCodec *dec;
  71. int ret;
  72. if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
  73. av_log(NULL, AV_LOG_ERROR, "Cannot open input file %s\n", filename);
  74. return ret;
  75. }
  76. if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  77. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  78. return ret;
  79. }
  80. /* select the audio stream */
  81. ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
  82. if (ret < 0) {
  83. av_log(NULL, AV_LOG_ERROR, "Cannot find an audio stream in the input file\n");
  84. return ret;
  85. }
  86. audio_stream_index = ret;
  87. /* create decoding context */
  88. dec_ctx = avcodec_alloc_context3(dec);
  89. if (!dec_ctx)
  90. return AVERROR(ENOMEM);
  91. avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[audio_stream_index]->codecpar);
  92. /* init the audio decoder */
  93. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  94. av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
  95. return ret;
  96. }
  97. return 0;
  98. }
  99. static int init_filters(const char *filters_descr)
  100. {
  101. char args[512];
  102. int ret = 0;
  103. const AVFilter *abuffersrc = avfilter_get_by_name("abuffer");
  104. const AVFilter *abuffersink = avfilter_get_by_name("abuffersink");
  105. AVFilterInOut *outputs = avfilter_inout_alloc();
  106. AVFilterInOut *inputs = avfilter_inout_alloc();
  107. static const enum AVSampleFormat out_sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE };
  108. static const int out_sample_rates[] = { 16000, -1 };
  109. const AVFilterLink *outlink;
  110. AVRational time_base = fmt_ctx->streams[audio_stream_index]->time_base;
  111. filter_graph = avfilter_graph_alloc();
  112. if (!outputs || !inputs || !filter_graph) {
  113. ret = AVERROR(ENOMEM);
  114. goto end;
  115. }
  116. /* buffer audio source: the decoded frames from the decoder will be inserted here. */
  117. if (dec_ctx->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
  118. av_channel_layout_default(&dec_ctx->ch_layout, dec_ctx->ch_layout.nb_channels);
  119. ret = snprintf(args, sizeof(args),
  120. "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=",
  121. time_base.num, time_base.den, dec_ctx->sample_rate,
  122. av_get_sample_fmt_name(dec_ctx->sample_fmt));
  123. av_channel_layout_describe(&dec_ctx->ch_layout, args + ret, sizeof(args) - ret);
  124. ret = avfilter_graph_create_filter(&buffersrc_ctx, abuffersrc, "in",
  125. args, NULL, filter_graph);
  126. if (ret < 0) {
  127. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
  128. goto end;
  129. }
  130. /* buffer audio sink: to terminate the filter chain. */
  131. ret = avfilter_graph_create_filter(&buffersink_ctx, abuffersink, "out",
  132. NULL, NULL, filter_graph);
  133. if (ret < 0) {
  134. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
  135. goto end;
  136. }
  137. ret = av_opt_set_int_list(buffersink_ctx, "sample_fmts", out_sample_fmts, -1,
  138. AV_OPT_SEARCH_CHILDREN);
  139. if (ret < 0) {
  140. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
  141. goto end;
  142. }
  143. ret = av_opt_set(buffersink_ctx, "ch_layouts", "mono",
  144. AV_OPT_SEARCH_CHILDREN);
  145. if (ret < 0) {
  146. av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
  147. goto end;
  148. }
  149. ret = av_opt_set_int_list(buffersink_ctx, "sample_rates", out_sample_rates, -1,
  150. AV_OPT_SEARCH_CHILDREN);
  151. if (ret < 0) {
  152. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
  153. goto end;
  154. }
  155. /*
  156. * Set the endpoints for the filter graph. The filter_graph will
  157. * be linked to the graph described by filters_descr.
  158. */
  159. /*
  160. * The buffer source output must be connected to the input pad of
  161. * the first filter described by filters_descr; since the first
  162. * filter input label is not specified, it is set to "in" by
  163. * default.
  164. */
  165. outputs->name = av_strdup("in");
  166. outputs->filter_ctx = buffersrc_ctx;
  167. outputs->pad_idx = 0;
  168. outputs->next = NULL;
  169. /*
  170. * The buffer sink input must be connected to the output pad of
  171. * the last filter described by filters_descr; since the last
  172. * filter output label is not specified, it is set to "out" by
  173. * default.
  174. */
  175. inputs->name = av_strdup("out");
  176. inputs->filter_ctx = buffersink_ctx;
  177. inputs->pad_idx = 0;
  178. inputs->next = NULL;
  179. if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
  180. &inputs, &outputs, NULL)) < 0)
  181. goto end;
  182. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
  183. goto end;
  184. /* Print summary of the sink buffer
  185. * Note: args buffer is reused to store channel layout string */
  186. outlink = buffersink_ctx->inputs[0];
  187. av_channel_layout_describe(&outlink->ch_layout, args, sizeof(args));
  188. av_log(NULL, AV_LOG_INFO, "Output: srate:%dHz fmt:%s chlayout:%s\n",
  189. (int)outlink->sample_rate,
  190. (char *)av_x_if_null(av_get_sample_fmt_name((AVSampleFormat)outlink->format), "?"),
  191. args);
  192. end:
  193. avfilter_inout_free(&inputs);
  194. avfilter_inout_free(&outputs);
  195. return ret;
  196. }
  197. static void sherpa_decode_frame(const AVFrame *frame, SherpaNcnnRecognizer *recognizer, SherpaNcnnStream *s, SherpaNcnnDisplay * display, int *segment_id)
  198. {
  199. #define N 3200 // 0.2 s. Sample rate is fixed to 16 kHz
  200. static float samples[N];
  201. static int nb_samples = 0;
  202. const int16_t *p = (int16_t*)frame->data[0];
  203. if (frame->nb_samples + nb_samples >= N) {
  204. AcceptWaveform(s, 16000, samples, nb_samples);
  205. while (IsReady(recognizer, s)) {
  206. Decode(recognizer, s);
  207. }
  208. SherpaNcnnResult *r = GetResult(recognizer, s);
  209. if (strlen(r->text)) {
  210. SherpaNcnnPrint(display, *segment_id, r->text);
  211. }
  212. if (IsEndpoint(recognizer, s)) {
  213. Reset(recognizer, s);
  214. if (strlen(r->text)) {
  215. ++(*segment_id);
  216. }
  217. }
  218. DestroyResult(r);
  219. nb_samples = 0;
  220. }
  221. for (int i = 0; i < frame->nb_samples; i++) {
  222. samples[nb_samples++] = p[i] / 32768.;
  223. }
  224. }
  225. static inline char *__av_err2str(int errnum)
  226. {
  227. static char str[AV_ERROR_MAX_STRING_SIZE];
  228. memset(str, 0, sizeof(str));
  229. return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
  230. }
  231. int main(int argc, char **argv)
  232. {
  233. int ret;
  234. int num_threads = 4;
  235. AVPacket *packet = av_packet_alloc();
  236. AVFrame *frame = av_frame_alloc();
  237. AVFrame *filt_frame = av_frame_alloc();
  238. const char *kUsage =
  239. "\n"
  240. "Usage:\n"
  241. " ./sherpa-ncnn-ffmpeg \\\n"
  242. " /path/to/tokens.txt \\\n"
  243. " /path/to/encoder.ncnn.param \\\n"
  244. " /path/to/encoder.ncnn.bin \\\n"
  245. " /path/to/decoder.ncnn.param \\\n"
  246. " /path/to/decoder.ncnn.bin \\\n"
  247. " /path/to/joiner.ncnn.param \\\n"
  248. " /path/to/joiner.ncnn.bin \\\n"
  249. " /path/to/foo.wav [<num_threads> [decode_method, can be "
  250. "greedy_search/modified_beam_search]]"
  251. "\n\n"
  252. "Please refer to \n"
  253. "https://k2-fsa.github.io/sherpa/ncnn/pretrained_models/index.html\n"
  254. "for a list of pre-trained models to download.\n";
  255. if (!packet || !frame || !filt_frame) {
  256. fprintf(stderr, "Could not allocate frame or packet\n");
  257. exit(1);
  258. }
  259. if (argc < 9 || argc > 11) {
  260. fprintf(stderr, "%s\n", kUsage);
  261. return -1;
  262. }
  263. SherpaNcnnRecognizerConfig config;
  264. config.model_config.tokens = argv[1];
  265. config.model_config.encoder_param = argv[2];
  266. config.model_config.encoder_bin = argv[3];
  267. config.model_config.decoder_param = argv[4];
  268. config.model_config.decoder_bin = argv[5];
  269. config.model_config.joiner_param = argv[6];
  270. config.model_config.joiner_bin = argv[7];
  271. if (argc >= 10 && atoi(argv[9]) > 0) {
  272. num_threads = atoi(argv[9]);
  273. }
  274. config.model_config.num_threads = num_threads;
  275. config.model_config.use_vulkan_compute = 0;
  276. config.decoder_config.decoding_method = "greedy_search";
  277. if (argc == 11) {
  278. config.decoder_config.decoding_method = argv[10];
  279. }
  280. config.decoder_config.num_active_paths = 4;
  281. config.enable_endpoint = 1;
  282. config.rule1_min_trailing_silence = 2.4;
  283. config.rule2_min_trailing_silence = 1.2;
  284. config.rule3_min_utterance_length = 300;
  285. config.feat_config.sampling_rate = 16000;
  286. config.feat_config.feature_dim = 80;
  287. SherpaNcnnRecognizer *recognizer = CreateRecognizer(&config);
  288. SherpaNcnnStream *s = CreateStream(recognizer);
  289. SherpaNcnnDisplay *display = CreateDisplay(60);
  290. int segment_id = 0;
  291. if ((ret = open_input_file(argv[8])) < 0)
  292. exit(1);
  293. if ((ret = init_filters(filter_descr)) < 0)
  294. exit(1);
  295. /* read all packets */
  296. while (1) {
  297. if ((ret = av_read_frame(fmt_ctx, packet)) < 0)
  298. break;
  299. if (packet->stream_index == audio_stream_index) {
  300. ret = avcodec_send_packet(dec_ctx, packet);
  301. if (ret < 0) {
  302. av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
  303. break;
  304. }
  305. while (ret >= 0) {
  306. ret = avcodec_receive_frame(dec_ctx, frame);
  307. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  308. break;
  309. } else if (ret < 0) {
  310. av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
  311. exit(1);
  312. }
  313. if (ret >= 0) {
  314. /* push the audio data from decoded frame into the filtergraph */
  315. if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
  316. av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
  317. break;
  318. }
  319. /* pull filtered audio from the filtergraph */
  320. while (1) {
  321. ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
  322. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  323. break;
  324. if (ret < 0)
  325. exit(1);
  326. sherpa_decode_frame(filt_frame, recognizer, s, display, &segment_id);
  327. av_frame_unref(filt_frame);
  328. }
  329. av_frame_unref(frame);
  330. }
  331. }
  332. }
  333. av_packet_unref(packet);
  334. }
  335. // add some tail padding
  336. float tail_paddings[4800] = {0}; // 0.3 seconds at 16 kHz sample rate
  337. AcceptWaveform(s, 16000, tail_paddings, 4800);
  338. InputFinished(s);
  339. while (IsReady(recognizer, s)) {
  340. Decode(recognizer, s);
  341. }
  342. SherpaNcnnResult *r = GetResult(recognizer, s);
  343. if(strlen(r->text)) {
  344. SherpaNcnnPrint(display, segment_id, r->text);
  345. }
  346. DestroyResult(r);
  347. DestroyDisplay(display);
  348. DestroyStream(s);
  349. DestroyRecognizer(recognizer);
  350. avfilter_graph_free(&filter_graph);
  351. avcodec_free_context(&dec_ctx);
  352. avformat_close_input(&fmt_ctx);
  353. av_packet_free(&packet);
  354. av_frame_free(&frame);
  355. av_frame_free(&filt_frame);
  356. if (ret < 0 && ret != AVERROR_EOF) {
  357. fprintf(stderr, "Error occurred: %s\n", __av_err2str(ret));
  358. exit(1);
  359. }
  360. fprintf(stderr, "\n");
  361. return 0;
  362. }