From ce4dd176e4c914272691e3aa54e3c9895f6ea4b7 Mon Sep 17 00:00:00 2001 From: Fangjun Kuang Date: Fri, 24 Feb 2023 17:44:36 +0800 Subject: [PATCH] Add ffmpeg example (#61) --- .github/scripts/test-online-transducer.sh | 11 + .github/workflows/linux.yaml | 32 ++ .gitignore | 1 + build-aarch64-linux-gnu.sh | 1 + c-api-examples/Makefile | 6 +- c-api-examples/decode-file-c-api.c | 5 +- c-api-examples/run.sh | 34 ++ cmake/portaudio.cmake | 1 + ffmpeg-examples/Makefile | 61 ++++ ffmpeg-examples/README.md | 16 + ffmpeg-examples/how-to-fix-errors.md | 34 ++ ffmpeg-examples/run.sh | 43 +++ ffmpeg-examples/sherpa-onnx-ffmpeg.c | 390 ++++++++++++++++++++++ 13 files changed, 632 insertions(+), 3 deletions(-) create mode 100755 c-api-examples/run.sh create mode 100644 ffmpeg-examples/Makefile create mode 100644 ffmpeg-examples/README.md create mode 100644 ffmpeg-examples/how-to-fix-errors.md create mode 100755 ffmpeg-examples/run.sh create mode 100644 ffmpeg-examples/sherpa-onnx-ffmpeg.c diff --git a/.github/scripts/test-online-transducer.sh b/.github/scripts/test-online-transducer.sh index f2f94530..c92971b8 100755 --- a/.github/scripts/test-online-transducer.sh +++ b/.github/scripts/test-online-transducer.sh @@ -141,4 +141,15 @@ for wave in ${waves[@]}; do 4 done +# Decode a URL +if [ $EXE == "sherpa-onnx-ffmpeg" ]; then + time $EXE \ + $repo/tokens.txt \ + $repo/encoder-epoch-99-avg-1.onnx \ + $repo/decoder-epoch-99-avg-1.onnx \ + $repo/joiner-epoch-99-avg-1.onnx \ + https://huggingface.co/csukuangfj/sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/resolve/main/test_wavs/4.wav \ + 4 +fi + rm -rf $repo diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux.yaml index d8f137f2..4870fc4b 100644 --- a/.github/workflows/linux.yaml +++ b/.github/workflows/linux.yaml @@ -10,6 +10,9 @@ on: - 'CMakeLists.txt' - 'cmake/**' - 'sherpa-onnx/csrc/*' + - 'sherpa-onnx/c-api/*' + - 'ffmpeg-examples/**' + - 'c-api-examples/**' pull_request: branches: - master @@ -19,6 +22,8 @@ on: - 'CMakeLists.txt' - 'cmake/**' - 'sherpa-onnx/csrc/*' + - 'sherpa-onnx/c-api/*' + - 'ffmpeg-examples/**' concurrency: group: linux-${{ github.ref }} @@ -40,6 +45,23 @@ jobs: with: fetch-depth: 0 + - name: Install ffmpeg + shell: bash + run: | + sudo apt-get install -y software-properties-common + sudo add-apt-repository ppa:savoury1/ffmpeg4 + sudo add-apt-repository ppa:savoury1/ffmpeg5 + + sudo apt-get install -y libavdevice-dev libavutil-dev ffmpeg + pkg-config --modversion libavutil + ffmpeg -version + + - name: Show ffmpeg version + shell: bash + run: | + pkg-config --modversion libavutil + ffmpeg -version + - name: Configure CMake shell: bash run: | @@ -56,12 +78,22 @@ jobs: ls -lh lib ls -lh bin + cd ../ffmpeg-examples + make + - name: Display dependencies of sherpa-onnx for linux shell: bash run: | file build/bin/sherpa-onnx readelf -d build/bin/sherpa-onnx + - name: Test sherpa-onnx-ffmpeg + run: | + export PATH=$PWD/ffmpeg-examples:$PATH + export EXE=sherpa-onnx-ffmpeg + + .github/scripts/test-online-transducer.sh + - name: Test online transducer shell: bash run: | diff --git a/.gitignore b/.gitignore index dc7d32ef..4e781377 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ run-*-zipformer.sh run-zh.sh decode-file-c-api run-decode-file-c-api.sh +sherpa-onnx-ffmpeg diff --git a/build-aarch64-linux-gnu.sh b/build-aarch64-linux-gnu.sh index 3712b3ca..d483eede 100755 --- a/build-aarch64-linux-gnu.sh +++ b/build-aarch64-linux-gnu.sh @@ -39,6 +39,7 @@ cmake \ -DBUILD_SHARED_LIBS=OFF \ -DSHERPA_ONNX_ENABLE_TESTS=OFF \ -DSHERPA_ONNX_ENABLE_PYTHON=OFF \ + -DSHERPA_ONNX_ENABLE_CHECK=OFF \ -DCMAKE_TOOLCHAIN_FILE=../toolchains/aarch64-linux-gnu.toolchain.cmake \ .. diff --git a/c-api-examples/Makefile b/c-api-examples/Makefile index 6e54e242..14e38ad4 100644 --- a/c-api-examples/Makefile +++ b/c-api-examples/Makefile @@ -1,10 +1,12 @@ +CUR_DIR :=$(shell pwd) + CFLAGS := -I ../ LDFLAGS := -L ../build/lib LDFLAGS += -L ../build/_deps/onnxruntime-src/lib LDFLAGS += -lsherpa-onnx-c-api -lsherpa-onnx-core -lonnxruntime -lkaldi-native-fbank-core -LDFLAGS += -Wl,-rpath,../build/lib -LDFLAGS += -Wl,-rpath,../build/_deps/onnxruntime-src/lib +LDFLAGS += -Wl,-rpath,${CUR_DIR}/../build/lib +LDFLAGS += -Wl,-rpath,${CUR_DIR}/../build/_deps/onnxruntime-src/lib decode-file-c-api: decode-file-c-api.c $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS) diff --git a/c-api-examples/decode-file-c-api.c b/c-api-examples/decode-file-c-api.c index ddd67fe9..f7a7d2e1 100644 --- a/c-api-examples/decode-file-c-api.c +++ b/c-api-examples/decode-file-c-api.c @@ -1,7 +1,10 @@ -// c-api-examples/decode-file-c-api.cc +// c-api-examples/decode-file-c-api.c // // Copyright (c) 2023 Xiaomi Corporation +// This file shows how to use sherpa-onnx C API +// to decode a file. + #include #include #include diff --git a/c-api-examples/run.sh b/c-api-examples/run.sh new file mode 100755 index 00000000..ac986cf9 --- /dev/null +++ b/c-api-examples/run.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash + +set -ex + +if [ ! -d ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20 ]; then + echo "Please download the pre-trained model for testing." + echo "You can refer to" + echo "" + echo "https://k2-fsa.github.io/sherpa/onnx/pretrained_models/zipformer-transducer-models.html#sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20-bilingual-chinese-english" + echo "for help" + exit 1 +fi + +if [[ ! -f ../build/lib/libsherpa-onnx-core.a && ! -f ../build/lib/libsherpa-onnx-core.dylib && ! -f ../build/lib/libsherpa-onnx-core.so ]]; then + echo "Please build sherpa-onnx first. You can use" + echo "" + echo " cd /path/to/sherpa-onnx" + echo " mkdir build" + echo " cd build" + echo " cmake .." + echo " make -j4" + exit 1 +fi + +if [ ! -f ./decode-file-c-api ]; then + make +fi + +./decode-file-c-api \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/tokens.txt \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/encoder-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/decoder-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/joiner-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/test_wavs/0.wav diff --git a/cmake/portaudio.cmake b/cmake/portaudio.cmake index 594dbe73..ac8f74d1 100644 --- a/cmake/portaudio.cmake +++ b/cmake/portaudio.cmake @@ -12,6 +12,7 @@ function(download_portaudio) ${PROJECT_SOURCE_DIR}/pa_stable_v190700_20210406.tgz ${PROJECT_BINARY_DIR}/pa_stable_v190700_20210406.tgz /tmp/pa_stable_v190700_20210406.tgz + /star-fj/fangjun/download/github/pa_stable_v190700_20210406.tgz ) foreach(f IN LISTS possible_file_locations) diff --git a/ffmpeg-examples/Makefile b/ffmpeg-examples/Makefile new file mode 100644 index 00000000..b232ec18 --- /dev/null +++ b/ffmpeg-examples/Makefile @@ -0,0 +1,61 @@ +CC=g++ +GDB ?= FALSE + +# use pkg-config for getting CFLAGS and LDLIBS +SHARED_LIBS=libavdevice \ + libavformat \ + libavfilter \ + libavcodec \ + libswresample \ + libswscale \ + libavutil + +ifeq ($(GDB), TRUE) + OPTFLAG += -g +endif + +CFLAGS := $(shell pkg-config --cflags $(SHARED_LIBS)) -I.. -Wall -std=c++11 -fopenmp ${OPTFLAG} +LDLIBS := $(shell pkg-config --libs $(SHARED_LIBS)) + +CUR_DIR :=$(shell pwd) + +LDLIBS += -L ../build/lib +LDLIBS += -L ../build/_deps/onnxruntime-src/lib +LDLIBS += -lsherpa-onnx-c-api -lsherpa-onnx-core -lonnxruntime -lkaldi-native-fbank-core +LDLIBS += -Wl,-rpath,${CUR_DIR}/../build/lib +LDLIBS += -Wl,-rpath,${CUR_DIR}/../build/_deps/onnxruntime-src/lib + + +#Get libavutil version and extract major, minor and micro +LIBAVUTIL_VERSION := $(shell pkg-config --modversion libavutil) +LIBAVUTIL_MAJOR := $(shell echo "$(LIBAVUTIL_VERSION)" | awk -F. '{print $$1}') +LIBAVUTIL_MINOR := $(shell echo "$(LIBAVUTIL_VERSION)" | awk -F. '{print $$2}') +LIBAVUTIL_MICRO := $(shell echo "$(LIBAVUTIL_VERSION)" | awk -F. '{print $$3}') +#Check if libavutil version is 57.28.100 or above +FFMPEG_51_AND_ABOVE = $(shell echo "$(LIBAVUTIL_MAJOR) $(LIBAVUTIL_MINOR) $(LIBAVUTIL_MICRO)" | awk '{if ($$1 > 57 || ($$1 == 57 && $$2 > 28) || ($$1 == 57 && $$2 == 28 && $$3 >= 100)) print "TRUE"; else print "FALSE"}') +ifeq ($(FFMPEG_51_AND_ABOVE), FALSE) +$(error FFmpeg version should be n5.1 or above!) +endif + +EXAMPLES=sherpa-onnx-ffmpeg + +OBJS=$(addsuffix .o,$(EXAMPLES)) + +.phony: all clean + +all: $(EXAMPLES) + @echo $(EXAMPLES) + $(RM) $(OBJS) + +$(EXAMPLES): $(OBJS) + $(CC) $(addsuffix .o,$@) $(CFLAGS) $(LDLIBS) -o $@ + +%.o : %.c + ${CC} ${CFLAGS} -c -o $@ $< + +clean: + $(RM) $(EXAMPLES) $(OBJS) + +build_info: + @echo "libavutil version: $(LIBAVUTIL_VERSION)" + @echo "Supported examples: $(EXAMPLES)" diff --git a/ffmpeg-examples/README.md b/ffmpeg-examples/README.md new file mode 100644 index 00000000..a69a89c7 --- /dev/null +++ b/ffmpeg-examples/README.md @@ -0,0 +1,16 @@ +# Introduction + +You can use `sherpa-onnx-ffmpeg` to decode a wav, mp3, or even a URL. + +See +for more supported formats and protocols, e.g., +RTMP/WebRTC/HLS/HTTP-FLV/SRT/MPEG-DASH/GB28181. + + +## How to use + +Please have a look at + +``` +./run.sh +``` diff --git a/ffmpeg-examples/how-to-fix-errors.md b/ffmpeg-examples/how-to-fix-errors.md new file mode 100644 index 00000000..e9b0b3c7 --- /dev/null +++ b/ffmpeg-examples/how-to-fix-errors.md @@ -0,0 +1,34 @@ +# Fixes for errors + +To fix the following error: +``` +Package libavdevice was not found in the pkg-config search path. +``` +please run + +``` +sudo apt-get install libavdevice-dev +``` + +To fix the following error +``` +Makefile:28: *** FFmpeg version should be n5.1 or above!. Stop. +``` +please run +``` +sudo apt-get install software-properties-common +sudo add-apt-repository ppa:savoury1/ffmpeg4 +sudo add-apt-repository ppa:savoury1/ffmpeg5 +sudo apt-get update +sudo apt-get install ffmpeg --reinstall +sudo apt-get install libavutil-dev --reinstall +``` + +To fix the following error: +``` +ModuleNotFoundError: No module named 'apt_pkg' +``` +please run: +``` +sudo apt-get install python-apt +``` diff --git a/ffmpeg-examples/run.sh b/ffmpeg-examples/run.sh new file mode 100755 index 00000000..7e07747d --- /dev/null +++ b/ffmpeg-examples/run.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash + +set -ex + +if [ ! -d ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20 ]; then + echo "Please download the pre-trained model for testing." + echo "You can refer to" + echo "" + echo "https://k2-fsa.github.io/sherpa/onnx/pretrained_models/zipformer-transducer-models.html#sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20-bilingual-chinese-english" + echo "for help" + exit 1 +fi + +if [[ ! -f ../build/lib/libsherpa-onnx-core.a && ! -f ../build/lib/libsherpa-onnx-core.dylib && ! -f ../build/lib/libsherpa-onnx-core.so ]]; then + echo "Please build sherpa-onnx first. You can use" + echo "" + echo " cd /path/to/sherpa-onnx" + echo " mkdir build" + echo " cd build" + echo " cmake .." + echo " make -j4" + exit 1 +fi + +if [ ! -f ./sherpa-onnx-ffmpeg ]; then + make +fi + +../ffmpeg-examples/sherpa-onnx-ffmpeg \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/tokens.txt \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/encoder-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/decoder-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/joiner-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/test_wavs/4.wav + +echo "Decoding a URL" + +../ffmpeg-examples/sherpa-onnx-ffmpeg \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/tokens.txt \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/encoder-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/decoder-epoch-99-avg-1.onnx \ + ./sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/joiner-epoch-99-avg-1.onnx \ + https://huggingface.co/csukuangfj/sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20/resolve/main/test_wavs/4.wav diff --git a/ffmpeg-examples/sherpa-onnx-ffmpeg.c b/ffmpeg-examples/sherpa-onnx-ffmpeg.c new file mode 100644 index 00000000..28027d83 --- /dev/null +++ b/ffmpeg-examples/sherpa-onnx-ffmpeg.c @@ -0,0 +1,390 @@ +// ffmpeg-examples/sherpa-onnx-ffmpeg.c +// +// Copyright (c) 2023 Xiaomi Corporation +#include +#include +#include + +#include "sherpa-onnx/c-api/c-api.h" + + +/* + * Copyright (c) 2010 Nicolas George + * Copyright (c) 2011 Stefano Sabatini + * Copyright (c) 2012 Clément Bœsch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * @file audio decoding and filtering usage example + * @example sherpa-onnx-ffmpeg.c + * + * Demux, decode and filter audio input file, generate a raw audio + * file to be played with ffplay. + */ + +#include +extern "C" { +#include +#include +#include +#include +#include +#include +} + +static const char *filter_descr = "aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono"; + +static AVFormatContext *fmt_ctx; +static AVCodecContext *dec_ctx; +AVFilterContext *buffersink_ctx; +AVFilterContext *buffersrc_ctx; +AVFilterGraph *filter_graph; +static int audio_stream_index = -1; + +static int open_input_file(const char *filename) +{ + const AVCodec *dec; + int ret; + + if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot open input file %s\n", filename); + return ret; + } + + if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n"); + return ret; + } + + /* select the audio stream */ + ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0); + if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot find an audio stream in the input file\n"); + return ret; + } + audio_stream_index = ret; + + /* create decoding context */ + dec_ctx = avcodec_alloc_context3(dec); + if (!dec_ctx) + return AVERROR(ENOMEM); + avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[audio_stream_index]->codecpar); + + /* init the audio decoder */ + if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n"); + return ret; + } + + return 0; +} + +static int init_filters(const char *filters_descr) +{ + char args[512]; + int ret = 0; + const AVFilter *abuffersrc = avfilter_get_by_name("abuffer"); + const AVFilter *abuffersink = avfilter_get_by_name("abuffersink"); + AVFilterInOut *outputs = avfilter_inout_alloc(); + AVFilterInOut *inputs = avfilter_inout_alloc(); + static const enum AVSampleFormat out_sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE }; + static const int out_sample_rates[] = { 16000, -1 }; + const AVFilterLink *outlink; + AVRational time_base = fmt_ctx->streams[audio_stream_index]->time_base; + + filter_graph = avfilter_graph_alloc(); + if (!outputs || !inputs || !filter_graph) { + ret = AVERROR(ENOMEM); + goto end; + } + + /* buffer audio source: the decoded frames from the decoder will be inserted here. */ + if (dec_ctx->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC) + av_channel_layout_default(&dec_ctx->ch_layout, dec_ctx->ch_layout.nb_channels); + ret = snprintf(args, sizeof(args), + "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=", + time_base.num, time_base.den, dec_ctx->sample_rate, + av_get_sample_fmt_name(dec_ctx->sample_fmt)); + av_channel_layout_describe(&dec_ctx->ch_layout, args + ret, sizeof(args) - ret); + ret = avfilter_graph_create_filter(&buffersrc_ctx, abuffersrc, "in", + args, NULL, filter_graph); + if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n"); + goto end; + } + + /* buffer audio sink: to terminate the filter chain. */ + ret = avfilter_graph_create_filter(&buffersink_ctx, abuffersink, "out", + NULL, NULL, filter_graph); + if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n"); + goto end; + } + + ret = av_opt_set_int_list(buffersink_ctx, "sample_fmts", out_sample_fmts, -1, + AV_OPT_SEARCH_CHILDREN); + if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n"); + goto end; + } + + ret = av_opt_set(buffersink_ctx, "ch_layouts", "mono", + AV_OPT_SEARCH_CHILDREN); + if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n"); + goto end; + } + + ret = av_opt_set_int_list(buffersink_ctx, "sample_rates", out_sample_rates, -1, + AV_OPT_SEARCH_CHILDREN); + if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n"); + goto end; + } + + /* + * Set the endpoints for the filter graph. The filter_graph will + * be linked to the graph described by filters_descr. + */ + + /* + * The buffer source output must be connected to the input pad of + * the first filter described by filters_descr; since the first + * filter input label is not specified, it is set to "in" by + * default. + */ + outputs->name = av_strdup("in"); + outputs->filter_ctx = buffersrc_ctx; + outputs->pad_idx = 0; + outputs->next = NULL; + + /* + * The buffer sink input must be connected to the output pad of + * the last filter described by filters_descr; since the last + * filter output label is not specified, it is set to "out" by + * default. + */ + inputs->name = av_strdup("out"); + inputs->filter_ctx = buffersink_ctx; + inputs->pad_idx = 0; + inputs->next = NULL; + + if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr, + &inputs, &outputs, NULL)) < 0) + goto end; + + if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0) + goto end; + + /* Print summary of the sink buffer + * Note: args buffer is reused to store channel layout string */ + outlink = buffersink_ctx->inputs[0]; + av_channel_layout_describe(&outlink->ch_layout, args, sizeof(args)); + av_log(NULL, AV_LOG_INFO, "Output: srate:%dHz fmt:%s chlayout:%s\n", + (int)outlink->sample_rate, + (char *)av_x_if_null(av_get_sample_fmt_name((AVSampleFormat)outlink->format), "?"), + args); + +end: + avfilter_inout_free(&inputs); + avfilter_inout_free(&outputs); + + return ret; +} + +static void sherpa_decode_frame(const AVFrame *frame, SherpaOnnxOnlineRecognizer *recognizer, + SherpaOnnxOnlineStream* stream) +{ +#define N 3200 // 100s. Sample rate is fixed to 16 kHz + static float samples[N]; + static int nb_samples = 0; + const int16_t *p = (int16_t*)frame->data[0]; + + if (frame->nb_samples + nb_samples > N) { + AcceptWaveform(stream, 16000, samples, nb_samples); + while (IsOnlineStreamReady(recognizer, stream)) { + DecodeOnlineStream(recognizer, stream); + } + + + if (IsEndpoint(recognizer, stream)) { + SherpaOnnxOnlineRecognizerResult *r = + GetOnlineStreamResult(recognizer, stream); + if (strlen(r->text)) { + fprintf(stderr, "%s\n", r->text); + } + DestroyOnlineRecognizerResult(r); + } + nb_samples = 0; + } + + for (int i = 0; i < frame->nb_samples; i++) { + samples[nb_samples++] = p[i] / 32768.; + } +} + +static inline char *__av_err2str(int errnum) +{ + static char str[AV_ERROR_MAX_STRING_SIZE]; + memset(str, 0, sizeof(str)); + return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum); +} + +int main(int argc, char **argv) +{ + int ret; + int num_threads = 4; + AVPacket *packet = av_packet_alloc(); + AVFrame *frame = av_frame_alloc(); + AVFrame *filt_frame = av_frame_alloc(); + const char *kUsage = + "\n" + "Usage:\n" + " ./sherpa-onnx-ffmpeg \\\n" + " /path/to/tokens.txt \\\n" + " /path/to/encoder.onnx\\\n" + " /path/to/decoder.onnx\\\n" + " /path/to/joiner.onnx\\\n" + " /path/to/foo.wav [num_threads]" + "\n\n" + "Please refer to \n" + "https://k2-fsa.github.io/sherpa/onnx/pretrained_models/index.html\n" + "for a list of pre-trained models to download.\n"; + + + if (!packet || !frame || !filt_frame) { + fprintf(stderr, "Could not allocate frame or packet\n"); + exit(1); + } + + if (argc < 6 || argc > 7) { + fprintf(stderr, "%s\n", kUsage); + return -1; + } + + SherpaOnnxOnlineRecognizerConfig config; + config.model_config.tokens = argv[1]; + config.model_config.encoder = argv[2]; + config.model_config.decoder = argv[3]; + config.model_config.joiner = argv[4]; + + if (argc == 7 && atoi(argv[6]) > 0) { + num_threads = atoi(argv[6]); + } + config.model_config.num_threads = num_threads; + config.model_config.debug = 0; + + config.feat_config.sample_rate = 16000; + config.feat_config.feature_dim = 80; + + config.enable_endpoint = 1; + config.rule1_min_trailing_silence = 2.4; + config.rule2_min_trailing_silence = 1.2; + config.rule3_min_utterance_length = 300; + + SherpaOnnxOnlineRecognizer *recognizer = CreateOnlineRecognizer(&config); + SherpaOnnxOnlineStream *stream = CreateOnlineStream(recognizer); + + if ((ret = open_input_file(argv[5])) < 0) + exit(1); + + if ((ret = init_filters(filter_descr)) < 0) + exit(1); + + /* read all packets */ + while (1) { + if ((ret = av_read_frame(fmt_ctx, packet)) < 0) + break; + + if (packet->stream_index == audio_stream_index) { + ret = avcodec_send_packet(dec_ctx, packet); + if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n"); + break; + } + + while (ret >= 0) { + ret = avcodec_receive_frame(dec_ctx, frame); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { + break; + } else if (ret < 0) { + av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n"); + exit(1); + } + + if (ret >= 0) { + /* push the audio data from decoded frame into the filtergraph */ + if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) { + av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n"); + break; + } + + /* pull filtered audio from the filtergraph */ + while (1) { + ret = av_buffersink_get_frame(buffersink_ctx, filt_frame); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) + break; + if (ret < 0) + exit(1); + sherpa_decode_frame(filt_frame, recognizer, stream); + av_frame_unref(filt_frame); + } + av_frame_unref(frame); + } + } + } + av_packet_unref(packet); + } + + // add some tail padding + float tail_paddings[4800] = {0}; // 0.3 seconds at 16 kHz sample rate + AcceptWaveform(stream, 16000, tail_paddings, 4800); + InputFinished(stream); + + while (IsOnlineStreamReady(recognizer, stream)) { + DecodeOnlineStream(recognizer, stream); + } + + SherpaOnnxOnlineRecognizerResult *r = + GetOnlineStreamResult(recognizer, stream); + if (strlen(r->text)) { + fprintf(stderr, "%s\n", r->text); + } + + DestroyOnlineRecognizerResult(r); + + DestoryOnlineStream(stream); + DestroyOnlineRecognizer(recognizer); + + avfilter_graph_free(&filter_graph); + avcodec_free_context(&dec_ctx); + avformat_close_input(&fmt_ctx); + av_packet_free(&packet); + av_frame_free(&frame); + av_frame_free(&filt_frame); + + if (ret < 0 && ret != AVERROR_EOF) { + fprintf(stderr, "Error occurred: %s\n", __av_err2str(ret)); + exit(1); + } + + return 0; +}