Android音视频系列Android收藏集android开发

视频解码 FFmpeg for Android

2018-09-15  本文已影响20人  dongzi711

FFmpeg一共包含8个库:

1)avcodec:编解码(最重要的库)
2)avformat:封装格式处理
3)avfiler:滤镜特效处理
4)avdevice:各种设备的输入输出
5)avutil:工具库(大部分库都需要这个库的支持)
6)postpro:后加工
7)swresaple:音频采样数据格式转换
8)swscale:视频像素格式转换

FFmpeg解码流程图如下: 20170120092743479.png

FFmpeg解码函数简介:

1)av_register_all():注册所有组件
2)avformat_open_intput():打开视频文件
3)avformat_find_stream_info():获取视频文件信息
4)avcodec_find_decoder():查找解码器
5)avcode_open2():打开解码器
6)av_read_frame():从输入文件读取一帧压缩数据
7)avcodec_decode_video2():解压一帧压缩数据
8)avcodec_close():关闭解码器
9)avformat_close_input():关闭输入视频文件

FFmpeg使用

step1:

按照我上篇文章编译FFmpeg for Android获取到的.so库和include文件夹。然后在Android studio工程的app/libs目录下新建文件夹armeabi和include,再将.so库文件复制到app/libs/armeabi目录下,然后将include里的头文件复制到app/libs/include目录下:

QQ截图20180915114334.png

step2:

定义本地方法native 类似于抽象方法 该方法没有方法体, 是c代码实现该方法
public native String Video_decode(); 按“Alt+Enter”提示在c代码中生成方法方法名称,点击提示自动生成一个空方法。

public class MainActivity extends Activity {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
        System.loadLibrary("avcodec-58");
        System.loadLibrary("avdevice-58");
        System.loadLibrary("avfilter-7");
        System.loadLibrary("avformat-58");
        System.loadLibrary("avutil-56");
        System.loadLibrary("postproc-55");
        System.loadLibrary("swresample-3");
        System.loadLibrary("swscale-5");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input= Environment.getExternalStorageDirectory().getAbsolutePath()+"/video.mp4";
                String output= Environment.getExternalStorageDirectory().getAbsolutePath()+"/video.yuv";
                video_decode(input,output);
            }
        });

    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native void video_decode(String input,String output);
}

step3:

修改CMakeLists.txt文件:

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# TODO 设置构建本机库文件所需的 CMake的最小版本
cmake_minimum_required(VERSION 3.4.1)

# TODO 设置变量,方便底下使用
set(INC_DIR ${PROJECT_SOURCE_DIR}/libs/include)
set(LINK_DIR ${PROJECT_SOURCE_DIR}/libs/${ANDROID_ABI})


# TODO 添加so库对应的头文件目录
include_directories(${INC_DIR})

# TODO 引入so库,IMPORT代表从第三方引入的意思
add_library( avcodec-58 SHARED IMPORTED)
# TODO 设置编译的库文件存放的目录
set_target_properties( avcodec-58 PROPERTIES IMPORTED_LOCATION ${LINK_DIR}/libavcodec-58.so)

add_library( avfilter-7 SHARED IMPORTED)
set_target_properties( avfilter-7 PROPERTIES IMPORTED_LOCATION ${LINK_DIR}/libavfilter-7.so)

add_library( avformat-58 SHARED IMPORTED)
set_target_properties( avformat-58 PROPERTIES IMPORTED_LOCATION ${LINK_DIR}/libavformat-58.so)

add_library( avutil-56 SHARED IMPORTED)
set_target_properties( avutil-56 PROPERTIES IMPORTED_LOCATION ${LINK_DIR}/libavutil-56.so)

add_library( swresample-3 SHARED IMPORTED)
set_target_properties( swresample-3 PROPERTIES IMPORTED_LOCATION ${LINK_DIR}/libswresample-3.so)

add_library( swscale-5 SHARED IMPORTED)
set_target_properties( swscale-5 PROPERTIES IMPORTED_LOCATION ${LINK_DIR}/libswscale-5.so)



# TODO 添加自己写的 C/C++源文件
add_library( native-lib
             SHARED
             src/main/cpp/native-lib.c )

# TODO 依赖 NDK中的库
find_library( log-lib
              log )

# TODO 将目标库与 NDK中的库进行连接
target_link_libraries( native-lib
                        avcodec-58
                        avfilter-7
                        avformat-58
                        avutil-56
                        swresample-3
                        swscale-5
                       ${log-lib} )

step4:

开始在native-lib.c里面写解析代码了:

#include <jni.h>
#include <android/log.h>
#define LOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"jason",FORMAT,##__VA_ARGS__);
#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"jason",FORMAT,##__VA_ARGS__);

//封装格式
#include "libavformat/avformat.h"
//解码
#include "libavcodec/avcodec.h"
//缩放
#include "libswscale/swscale.h"

JNIEXPORT void JNICALL
Java_com_ffmpeg_1study_MainActivity_video_1decode(JNIEnv *env, jobject instance, jstring input_,
                                                  jstring output_) {
    const char *input_cstr = (*env)->GetStringUTFChars(env, input_, 0);
    const char *output_cstr = (*env)->GetStringUTFChars(env, output_, 0);


    //1.注册组件
    av_register_all();

    //封装格式上下文
    AVFormatContext *pFormatCtx = avformat_alloc_context();

    //2.打开输入视频文件
    if(avformat_open_input(&pFormatCtx,input_cstr,NULL,NULL) != 0){
        LOGE("%s","打开输入视频文件失败");
        return;
    }
    //3.获取视频信息
    if(avformat_find_stream_info(pFormatCtx,NULL) < 0){
        LOGE("%s","获取视频信息失败");
        return;
    }

    //视频解码,需要找到视频对应的AVStream所在pFormatCtx->streams的索引位置
    int video_stream_idx = -1;
    int i = 0;
    for(; i < pFormatCtx->nb_streams;i++){
        //根据类型判断,是否是视频流
        if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){
            video_stream_idx = i;
            break;
        }
    }

    //4.获取视频解码器
    AVCodecContext *pCodeCtx = pFormatCtx->streams[video_stream_idx]->codec;
    AVCodec *pCodec = avcodec_find_decoder(pCodeCtx->codec_id);
    if(pCodec == NULL){
        LOGE("%s","无法解码");
        return;
    }

    //5.打开解码器
    if(avcodec_open2(pCodeCtx,pCodec,NULL) < 0){
        LOGE("%s","解码器无法打开");
        return;
    }

    //编码数据
    AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));

    //像素数据(解码数据)
    AVFrame *frame = av_frame_alloc();
    AVFrame *yuvFrame = av_frame_alloc();

    //只有指定了AVFrame的像素格式、画面大小才能真正分配内存
    //缓冲区分配内存
    uint8_t *out_buffer = (uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodeCtx->width, pCodeCtx->height));
    //初始化缓冲区
    avpicture_fill((AVPicture *)yuvFrame, out_buffer, AV_PIX_FMT_YUV420P, pCodeCtx->width, pCodeCtx->height);


    //输出文件
    FILE* fp_yuv = fopen(output_cstr,"wb");

    //用于像素格式转换或者缩放
    struct SwsContext *sws_ctx = sws_getContext(
            pCodeCtx->width, pCodeCtx->height, pCodeCtx->pix_fmt,
            pCodeCtx->width, pCodeCtx->height, AV_PIX_FMT_YUV420P,
            SWS_BILINEAR, NULL, NULL, NULL);

    int len ,got_frame, framecount = 0;
    //6.一阵一阵读取压缩的视频数据AVPacket
    while(av_read_frame(pFormatCtx,packet) >= 0){
        //解码AVPacket->AVFrame
        len = avcodec_decode_video2(pCodeCtx, frame, &got_frame, packet);

        //Zero if no frame could be decompressed
        //非零,正在解码
        if(got_frame){
            //frame->yuvFrame (YUV420P)
            //转为指定的YUV420P像素帧
            sws_scale(sws_ctx,
                      frame->data,frame->linesize, 0, frame->height,
                      yuvFrame->data, yuvFrame->linesize);

            //向YUV文件保存解码之后的帧数据
            //AVFrame->YUV
            //一个像素包含一个Y
            int y_size = pCodeCtx->width * pCodeCtx->height;
            fwrite(yuvFrame->data[0], 1, y_size, fp_yuv);
            fwrite(yuvFrame->data[1], 1, y_size/4, fp_yuv);
            fwrite(yuvFrame->data[2], 1, y_size/4, fp_yuv);

            LOGI("解码%d帧",framecount++);
        }

        av_free_packet(packet);
    }

    fclose(fp_yuv);

    av_frame_free(&frame);
    avcodec_close(pCodeCtx);
    avformat_free_context(pFormatCtx);

    (*env)->ReleaseStringUTFChars(env, input_, input_cstr);
    (*env)->ReleaseStringUTFChars(env, output_, output_cstr);
}

step5:

在andriod studio面板的Gradle Script -> build.gradle(Module:app)
修改build.gradle文件,在android {……}的段里面,加上这段

    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }

在defaultConfig {……}的段里面,加上这段

 ndk {
            abiFilters 'armeabi'
            }

这样就可以编译运行了。

上一篇下一篇

猜你喜欢

热点阅读