sherpa-ncnn-ffmpeg.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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)
  198. {
  199. #define N 3200 // 100s. 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(recognizer, 16000, samples, nb_samples);
  205. Decode(recognizer);
  206. if (IsEndpoint(recognizer)) {
  207. SherpaNcnnResult *r = GetResult(recognizer);
  208. if (strlen(r->text)) {
  209. fprintf(stderr, "%s\n", r->text);
  210. }
  211. DestroyResult(r);
  212. }
  213. nb_samples = 0;
  214. }
  215. for (int i = 0; i < frame->nb_samples; i++) {
  216. samples[nb_samples++] = p[i] / 32768.;
  217. }
  218. }
  219. static inline char *__av_err2str(int errnum)
  220. {
  221. static char str[AV_ERROR_MAX_STRING_SIZE];
  222. memset(str, 0, sizeof(str));
  223. return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
  224. }
  225. int main(int argc, char **argv)
  226. {
  227. int ret;
  228. int num_threads = 4;
  229. AVPacket *packet = av_packet_alloc();
  230. AVFrame *frame = av_frame_alloc();
  231. AVFrame *filt_frame = av_frame_alloc();
  232. const char *kUsage =
  233. "\n"
  234. "Usage:\n"
  235. " ./sherpa-ncnn-ffmpeg \\\n"
  236. " /path/to/tokens.txt \\\n"
  237. " /path/to/encoder.ncnn.param \\\n"
  238. " /path/to/encoder.ncnn.bin \\\n"
  239. " /path/to/decoder.ncnn.param \\\n"
  240. " /path/to/decoder.ncnn.bin \\\n"
  241. " /path/to/joiner.ncnn.param \\\n"
  242. " /path/to/joiner.ncnn.bin \\\n"
  243. " /path/to/foo.wav [<num_threads> [decode_method, can be "
  244. "greedy_search/modified_beam_search]]"
  245. "\n\n"
  246. "Please refer to \n"
  247. "https://k2-fsa.github.io/sherpa/ncnn/pretrained_models/index.html\n"
  248. "for a list of pre-trained models to download.\n";
  249. if (!packet || !frame || !filt_frame) {
  250. fprintf(stderr, "Could not allocate frame or packet\n");
  251. exit(1);
  252. }
  253. if (argc < 9 || argc > 11) {
  254. fprintf(stderr, "%s\n", kUsage);
  255. return -1;
  256. }
  257. SherpaNcnnModelConfig model_config;
  258. model_config.tokens = argv[1];
  259. model_config.encoder_param = argv[2];
  260. model_config.encoder_bin = argv[3];
  261. model_config.decoder_param = argv[4];
  262. model_config.decoder_bin = argv[5];
  263. model_config.joiner_param = argv[6];
  264. model_config.joiner_bin = argv[7];
  265. if (argc >= 10 && atoi(argv[9]) > 0) {
  266. num_threads = atoi(argv[9]);
  267. }
  268. model_config.num_threads = num_threads;
  269. model_config.use_vulkan_compute = 0;
  270. SherpaNcnnDecoderConfig decoder_config;
  271. decoder_config.decoding_method = "greedy_search";
  272. if (argc == 11) {
  273. decoder_config.decoding_method = argv[10];
  274. }
  275. decoder_config.num_active_paths = 4;
  276. decoder_config.enable_endpoint = 1;
  277. decoder_config.rule1_min_trailing_silence = 2.4;
  278. decoder_config.rule2_min_trailing_silence = 1.2;
  279. decoder_config.rule3_min_utterance_length = 300;
  280. SherpaNcnnRecognizer *recognizer =
  281. CreateRecognizer(&model_config, &decoder_config);
  282. if ((ret = open_input_file(argv[8])) < 0)
  283. exit(1);
  284. if ((ret = init_filters(filter_descr)) < 0)
  285. exit(1);
  286. /* read all packets */
  287. while (1) {
  288. if ((ret = av_read_frame(fmt_ctx, packet)) < 0)
  289. break;
  290. if (packet->stream_index == audio_stream_index) {
  291. ret = avcodec_send_packet(dec_ctx, packet);
  292. if (ret < 0) {
  293. av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
  294. break;
  295. }
  296. while (ret >= 0) {
  297. ret = avcodec_receive_frame(dec_ctx, frame);
  298. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  299. break;
  300. } else if (ret < 0) {
  301. av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
  302. exit(1);
  303. }
  304. if (ret >= 0) {
  305. /* push the audio data from decoded frame into the filtergraph */
  306. if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
  307. av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
  308. break;
  309. }
  310. /* pull filtered audio from the filtergraph */
  311. while (1) {
  312. ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
  313. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  314. break;
  315. if (ret < 0)
  316. exit(1);
  317. sherpa_decode_frame(filt_frame, recognizer);
  318. av_frame_unref(filt_frame);
  319. }
  320. av_frame_unref(frame);
  321. }
  322. }
  323. }
  324. av_packet_unref(packet);
  325. }
  326. // add some tail padding
  327. float tail_paddings[4800] = {0}; // 0.3 seconds at 16 kHz sample rate
  328. AcceptWaveform(recognizer, 16000, tail_paddings, 4800);
  329. InputFinished(recognizer);
  330. Decode(recognizer);
  331. SherpaNcnnResult *r = GetResult(recognizer);
  332. fprintf(stderr, "%s\n", r->text);
  333. DestroyResult(r);
  334. DestroyRecognizer(recognizer);
  335. avfilter_graph_free(&filter_graph);
  336. avcodec_free_context(&dec_ctx);
  337. avformat_close_input(&fmt_ctx);
  338. av_packet_free(&packet);
  339. av_frame_free(&frame);
  340. av_frame_free(&filt_frame);
  341. if (ret < 0 && ret != AVERROR_EOF) {
  342. fprintf(stderr, "Error occurred: %s\n", __av_err2str(ret));
  343. exit(1);
  344. }
  345. return 0;
  346. }