1. 程式人生 > >Android 音視頻深入 十 FFmpeg給視頻加特效(附源碼下載)

Android 音視頻深入 十 FFmpeg給視頻加特效(附源碼下載)

frame avi sca desc github cor 濾波器 struct find

項目地址,求star
https://github.com/979451341/Audio-and-video-learning-materials/tree/master/FFmpeg(AVfilter%E8%BF%87%E6%BB%A4%EF%BC%89

1.AVfilter結構體成員

這個特效要靠AVfilter來實現,首先說一下說AVfilter這個結構體的成員

/

*過濾器定義。這定義了一個過濾器包含的墊,以及所有的

*用於與篩選器交互的回調函數。

  • /
    typedef struct AVFilter {

/

*過濾器名稱。在過濾器中必須是非空且唯一的。

  • /

    const char *name;

/

*描述濾波器。可能是空的。

*

你應該使用null_if_config_small()宏定義。

  • /

    const char *description;

/

*輸入清單,由零元終止。

*

*如果沒有(靜態)輸入,則為null。過濾器實例

  • avfilter_flag_dynamic_inputs集可能會有比現在更多的投入

*這份清單。

  • /

    const AVFilterPad *inputs;

/

*輸出清單,由零元終止。

*

*如果沒有(靜態)輸出,則為null。過濾器實例

  • avfilter_flag_dynamic_outputs集可能會有比現在更多的產出

*這份清單。

  • /

    const AVFilterPad *outputs;

/

*一個私人數據的類,用於聲明私人avoptions過濾器。

*此字段對於未聲明任何選項的篩選器無效。

*

*如果該字段非空,則是篩選私有數據的第一個成員。

*必須是指針對avclass,這將由libavfilter通用

*這個類的代碼。

  • /

    const AVClass *priv_class;

/

結合avfilterflag

  • /

    int flags;

2.AVfilter使用步驟

現在直接在代碼上說這個AVfilter使用的步驟

因為使用濾鏡,所以需要播放視頻,就要解碼,來段標準準備代碼

// sd卡中的視頻文件地址,可自行修改或者通過jni傳入
char *file_name = "/storage/emulated/0/pauseRecordDemo/video/2018-02-03-09-25-34.mp4";
//char *file_name = "/storage/emulated/0/video.avi";

av_register_all();

//註冊所有AVFilter。
avfilter_register_all();//added by ws for AVfilter

AVFormatContext *pFormatCtx = avformat_alloc_context();

// Open video file
if (avformat_open_input(&pFormatCtx, file_name, NULL, NULL) != 0) {

    LOGD("Couldn‘t open file:%s\n", file_name);
    return -1; // Couldn‘t open file
}

// Retrieve stream information
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
    LOGD("Couldn‘t find stream information.");
    return -1;
}

// Find the first video stream
int videoStream = -1, i;
for (i = 0; i < pFormatCtx->nb_streams; i++) {
    if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO
        && videoStream < 0) {
        videoStream = i;
    }
}
if (videoStream == -1) {
    LOGD("Didn‘t find a video stream.");
    return -1; // Didn‘t find a video stream
}

// Get a pointer to the codec context for the video stream
AVCodecContext *pCodecCtx = pFormatCtx->streams[videoStream]->codec;

開始濾鏡的準備

AVFilter *buffersrc  = avfilter_get_by_name("buffer");
AVFilter *buffersink = avfilter_get_by_name("buffersink");//新版的ffmpeg庫必須為buffersink
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs  = avfilter_inout_alloc();
enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
AVBufferSinkParams *buffersink_params;

//為FilterGraph分配內存。
filter_graph = avfilter_graph_alloc();
//創建並向FilterGraph中添加一個Filter。
ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
args, NULL, filter_graph);
if (ret < 0) {
LOGD("Cannot create buffer source\n");
return ret;
}

buffersink_params = av_buffersink_params_alloc();
buffersink_params->pixel_fmts = pix_fmts;

//創建並向FilterGraph中添加一個Filter。
ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
NULL, buffersink_params, filter_graph);
av_free(buffersink_params);
if (ret < 0) {
LOGD("Cannot create buffer sink\n");
return ret;
}

給AVfilter的輸入輸出描述賦值

outputs->name       = av_strdup("in");
outputs->filter_ctx = buffersrc_ctx;
outputs->pad_idx    = 0;
outputs->next       = NULL;

inputs->name       = av_strdup("out");
inputs->filter_ctx = buffersink_ctx;
inputs->pad_idx    = 0;
inputs->next       = NULL;

配置和使用濾鏡效果,改變u、v這個兩個像素,使畫面顯示黑白

const char *filters_descr = "lutyuv=‘u=128:v=128‘";

//將一串通過字符串描述的Graph添加到FilterGraph中。
if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
&inputs, &outputs, NULL)) < 0) {
LOGD("Cannot avfilter_graph_parse_ptr\n");
return ret;
}
//檢查FilterGraph的配置。
if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0) {
LOGD("Cannot avfilter_graph_config\n");
return ret;
}

接下來就是渲染

// Find the decoder for the video stream
AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
    LOGD("Codec not found.");
    return -1; // Codec not found
}

if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
    LOGD("Could not open codec.");
    return -1; // Could not open codec
}

// 獲取native window
ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, surface);

// 獲取視頻寬高
int videoWidth = pCodecCtx->width;
int videoHeight = pCodecCtx->height;

// 設置native window的buffer大小,可自動拉伸
ANativeWindow_setBuffersGeometry(nativeWindow, videoWidth, videoHeight,
                                 WINDOW_FORMAT_RGBA_8888);
ANativeWindow_Buffer windowBuffer;

if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
    LOGD("Could not open codec.");
    return -1; // Could not open codec
}

// Allocate video frame
AVFrame *pFrame = av_frame_alloc();

// 用於渲染
AVFrame *pFrameRGBA = av_frame_alloc();
if (pFrameRGBA == NULL || pFrame == NULL) {
    LOGD("Could not allocate video frame.");
    return -1;
}

// Determine required buffer size and allocate buffer
// buffer中數據就是用於渲染的,且格式為RGBA
int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGBA, pCodecCtx->width, pCodecCtx->height,
                                        1);
uint8_t *buffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));
av_image_fill_arrays(pFrameRGBA->data, pFrameRGBA->linesize, buffer, AV_PIX_FMT_RGBA,
                     pCodecCtx->width, pCodecCtx->height, 1);

// 由於解碼出來的幀格式不是RGBA的,在渲染之前需要進行格式轉換
struct SwsContext *sws_ctx = sws_getContext(pCodecCtx->width,
                                            pCodecCtx->height,
                                            pCodecCtx->pix_fmt,
                                            pCodecCtx->width,
                                            pCodecCtx->height,
                                            AV_PIX_FMT_RGBA,
                                            SWS_BILINEAR,
                                            NULL,
                                            NULL,
                                            NULL);

解碼和釋放資源,在解碼的時候將解碼的數據放入FilterGraph去顯示

while (av_read_frame(pFormatCtx, &packet) >= 0) {
    // Is this a packet from the video stream?
    if (packet.stream_index == videoStream) {

        // Decode video frame
        avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);

        // 並不是decode一次就可解碼出一幀
        if (frameFinished) {

            //added by ws for AVfilter start
            pFrame->pts = av_frame_get_best_effort_timestamp(pFrame);

            //* 向FilterGraph中加入一個AVFrame。
            if (av_buffersrc_add_frame(buffersrc_ctx, pFrame) < 0) {
                LOGD("Could not av_buffersrc_add_frame");
                break;
            }

//從FilterGraph中取出一個AVFrame。
ret = av_buffersink_get_frame(buffersink_ctx, pFrame);
if (ret < 0) {
LOGD("Could not av_buffersink_get_frame");
break;
}
//added by ws for AVfilter end

            // lock native window buffer
            ANativeWindow_lock(nativeWindow, &windowBuffer, 0);

            // 格式轉換
            sws_scale(sws_ctx, (uint8_t const *const *) pFrame->data,
                      pFrame->linesize, 0, pCodecCtx->height,
                      pFrameRGBA->data, pFrameRGBA->linesize);

            // 獲取stride
            uint8_t *dst = (uint8_t *) windowBuffer.bits;
            int dstStride = windowBuffer.stride * 4;
            uint8_t *src = (pFrameRGBA->data[0]);
            int srcStride = pFrameRGBA->linesize[0];

            // 由於window的stride和幀的stride不同,因此需要逐行復制
            int h;
            for (h = 0; h < videoHeight; h++) {
                memcpy(dst + h * dstStride, src + h * srcStride, srcStride);
            }

            ANativeWindow_unlockAndPost(nativeWindow);
        }

    }
    av_packet_unref(&packet);
}

av_free(buffer);
av_free(pFrameRGBA);

// Free the YUV frame
av_free(pFrame);

avfilter_graph_free(&filter_graph); //added by ws for avfilter
// Close the codecs
avcodec_close(pCodecCtx);

這個想要真正掌握,需要將avfilter.c至少過個兩個遍,因為這下面四個結構體還沒有看看他們的內部成員

typedef struct AVFilterContext AVFilterContext;
typedef struct AVFilterLink AVFilterLink;
typedef struct AVFilterPad AVFilterPad;
typedef struct AVFilterFormats AVFilterFormats;

Android 音視頻深入 十 FFmpeg給視頻加特效(附源碼下載)