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

來源:互聯網
上載者:User

標籤:oid   setbuf   lib   清單   effort   sizeof   stride   []   pos   

項目地址,求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 fileif (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 informationif (avformat_find_stream_info(pFormatCtx, NULL) < 0) {    LOGD("Couldn‘t find stream information.");    return -1;}// Find the first video streamint 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 streamAVCodecContext *pCodecCtx = pFormatCtx->streams[videoStream]->codec;

開始濾鏡的準備

AVFilter *buffersrc  = avfilter_get_by_name("buffer");AVFilter *buffersink = avfilter_get_by_name("buffersink");//新版的ffmpeg庫必須為buffersinkAVFilterInOut *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 streamAVCodec *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 windowANativeWindow *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 frameAVFrame *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中資料就是用於渲染的,且格式為RGBAint 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 frameav_free(pFrame);avfilter_graph_free(&filter_graph); //added by ws for avfilter// Close the codecsavcodec_close(pCodecCtx);

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

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

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.