How to execute command line ffmpeg commands programatically in android?

女生的网名这么多〃 提交于 2019-12-05 17:09:32

Recently I came across the similar problem. My solution is to simulate a command line in Java program.

Firstly, I add a function to the file "ffmpeg.c":

int cmd_simulation(int argc, const char** argv)
{
OptionsContext o = { 0 };
// int64_t ti;

reset_options(&o, 0);

av_log_set_flags(AV_LOG_SKIP_REPEATED);
parse_loglevel(argc, argv, options);

if(argc>1 && !strcmp(argv[1], "-d")){
    run_as_daemon=1;
    av_log_set_callback(log_callback_null);
    argc--;
    argv++;
}

avcodec_register_all();

avfilter_register_all();
av_register_all();
avformat_network_init();

//show_banner(argc, argv, options);

term_init();

parse_cpuflags(argc, argv, options);

/* parse options */
parse_options(&o, argc, argv, options, opt_output_file);

if (nb_output_files <= 0 && nb_input_files == 0) {
    show_usage();
    av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
    exit_program(1);
}


if (nb_output_files <= 0) {
    av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
    exit_program(1);
}

if (transcode() < 0)
    exit_program(1);

//exit_program(0);
return 7;
}

In fact this function is just a copy of the main function with a little modification.

Then create a native function:

extern const char* cmd_simulation(int, const char**);

JNIEXPORT int JNICALL Java_com_test_videowatermark_VideoUtil_test(JNIEnv * env, jobject object, jobjectArray strArray);



JNIEXPORT int JNICALL Java_com_test_videowatermark_VideoUtil_test(JNIEnv * env, jobject object, jobjectArray strArray)
{
    int arrayLength = (*env)->GetArrayLength(env, strArray);
    const char* args[arrayLength];

    int i;
    for(i = 0; i < arrayLength; i++){
        jstring jstr = (jstring)((*env)->GetObjectArrayElement(env, strArray, i));
        args[i] = (*env)->GetStringUTFChars(env, jstr, 0);
        //strcpy(args[i], arg);
        //env->ReleaseStringUTFChars(jstr, arg);
    }


    const char** argv = args;
    return  cmd_simulation(arrayLength, argv);  

}

After compilation with ffmpeg, you can simulate excuting ffmpeg commands like:

private void executeCommand(){
    String[] command = {"ffmpeg", "-i", "some video file name",};
    int result = test(command);     
}

Hope this helps!

EDIT: Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_WHOLE_STATIC_LIBRARIES := libavformat libavcodec libavutil libpostproc libswscale libswresample libavfilter
LOCAL_MODULE    := VideoUtilLib
LOCAL_SRC_FILES := NativeVideoUtil.c ffmpeg.c ffmpeg_opt.c cmdutils.c ffmpeg_filter.c
LOCAL_LDLIBS := -lz -llog
include $(BUILD_SHARED_LIBRARY)
include $(call all-makefiles-under,$(LOCAL_PATH))

Replace NativeVideoUtil.c with your native file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!