热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

FFmpegFilter简单使用

本文主要分享【】,技术文章【FFmpegFilter简单使用】为【音视频开发老舅】投稿,如果你遇到音视频开发进阶相关问题,本文相关知识或能到你。Filter,可以认为是一些预定义的范式,可以实现

本文主要分享【】,技术文章【FFmpeg Filter简单使用】为【音视频开发老舅】投稿,如果你遇到音视频开发进阶相关问题,本文相关知识或能到你。

Filter,可以认为是一些预定义的范式,可以实现类似积木的多种功能的自由组合。每个filter都有固定数目的输入和输出,而且实际使用中不允许有空 悬的输入输出端。使用文本描述时我们可以通过标识符指定输入和输出端口,将不同filter串联起来,构成更复杂的filter。这就形成了嵌套的 filter。当然每个filter可以通过ffmpeg/ffplay命令行实现,但通常filter更方便。

Filter能做什么?

比较常见的有:

音视频的倍速播放

视频添加删除Logo

视频画中画

放大缩小

画面裁剪

源码

#include 
  
    #include 
   
     #include 
    
      #include 
     
       #include 
      
        #include 
       
         #include 
        
          #include 
         
           static AVFormatContext *fmt_ctx; static AVCodecContext *dec_ctx; AVFilterContext *buffersink_ctx; AVFilterContext *buffersrc_ctx; AVFilterGraph *filter_graph; static int video_stream_index = -1; //打开输入文件 static int open_input_file(const char *filename) { int ret; AVCodec *dec; if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) <0) { av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); 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; } //选择视频流 ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0); if (ret <0) { av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n"); return ret; } video_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[video_stream_index]->codecpar); //初始化解码器 if ((ret = avcodec_open2(dec_ctx, dec, NULL)) <0) { av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n"); return ret; } return 0; } //初始化filter static int init_filters(const char *filters_descr) { char args[512]; int ret = 0; //滤镜输入缓冲区,解码器解码后的数据都会放到buffer中,是一个特殊的filter const AVFilter *buffersrc = avfilter_get_by_name("buffer"); //滤镜输出缓冲区,滤镜处理完后输出的数据都会放在buffersink中,是一个特殊的filter const AVFilter *buffersink = avfilter_get_by_name("buffersink"); AVFilterInOut *outputs = avfilter_inout_alloc(); AVFilterInOut *inputs = avfilter_inout_alloc(); AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base; enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_YUV420P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE}; //创建filter图,会包含本次使用到的所有过滤器 filter_graph = avfilter_graph_alloc(); if (!outputs || !inputs || !filter_graph) { ret = AVERROR(ENOMEM); goto end; } /* buffer video source: the decoded frames from the decoder will be inserted here. */ snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den); //创建过滤器实例并将其添加到现有graph中 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in", args, NULL, filter_graph); if (ret <0) { av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n"); goto end; } /* 缓冲视频接收器: 终止过滤器链 */ ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out", NULL, NULL, filter_graph); if (ret <0) { av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n"); goto end; } ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts, AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN); if (ret <0) { av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\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; end: avfilter_inout_free(&inputs); avfilter_inout_free(&outputs); return ret; } //保存YUV数据 static int save_frame(AVFrame *filt_frame, FILE *out){ av_log(NULL, AV_LOG_DEBUG, "do_frame %d\n",filt_frame->format); if(filt_frame->format==AV_PIX_FMT_YUV420P){ av_log(NULL, AV_LOG_ERROR, "save 1 frame\n"); for(int i=0;i
          
           height;i++){ fwrite(filt_frame->data[0]+filt_frame->linesize[0]*i,1,filt_frame->width,out); } for(int i=0;i
           
            height/2;i++){ fwrite(filt_frame->data[1]+filt_frame->linesize[1]*i,1,filt_frame->width/2,out); } for(int i=0;i
            
             height/2;i++){ fwrite(filt_frame->data[2]+filt_frame->linesize[2]*i,1,filt_frame->width/2,out); } } fflush(out); return 0; } int main(int argc, char **argv) { int ret; AVPacket packet; AVFrame *frame; AVFrame *filt_frame; FILE *out = NULL; const char *filter_desc="movie=my_logo.png[wm];[in][wm]overlay=5:5[out]"; //左上角绘制一个logo图片 //"drawbox=30:10:64:64:red";//x= 30,y=10,/Users/liuwei/Desktop/test.mp4"; const char* outfile = "/Users/liuwei/Desktop/new_test.yuv"; av_log_set_level(AV_LOG_DEBUG); frame = av_frame_alloc(); filt_frame = av_frame_alloc(); if (!frame || !filt_frame) { perror("Could not allocate frame"); exit(1); } out = fopen(outfile, "wb"); if(!out){ av_log(NULL, AV_LOG_ERROR, "Failed to open yuv file!\n"); exit(-1); } if ((ret = open_input_file(filename)) <0) goto end; if ((ret = init_filters(filter_desc)) <0) goto end; /* read all packets */ while (1) { // 1 if ((ret = av_read_frame(fmt_ctx, &packet)) <0) break; if (packet.stream_index == video_stream_index) { //2 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) { //3 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"); goto end; } frame->pts = frame->best_effort_timestamp; /*4 push the 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 filtergraph\n"); break; } /* pull filtered frames from the filtergraph */ while (1) { //5 ret = av_buffersink_get_frame(buffersink_ctx, filt_frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; if (ret <0) goto end; save_frame(filt_frame,out); av_frame_unref(filt_frame); } av_frame_unref(frame); } } av_packet_unref(&packet); } end: avfilter_graph_free(&filter_graph); avcodec_free_context(&dec_ctx); avformat_close_input(&fmt_ctx); 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); } exit(0); } 
            
           
          
         
        
       
      
     
    
   
  

本文结尾底部,领取最新最全C++音视频学习提升资料,内容包括(C/C++Linux 服务器开发,FFmpeg webRTC rtmp hls rtsp ffplay srs↓↓↓↓↓↓文章底部

代码会将一个MP4文件在左上角添加一个图片后输出为yuv文件,这个图片如果背景是透明的就是水印啦(主要是懒得做透明背景图片)。

"drawbox=30:10:64:64:red";x= 30,y=10,width=64,height=64,color=red, 绘制一个红色正方形

`"scale=iw*2:ih*2"`视频缩放,iw 表示输入视频的宽,ih表示输入视频的高。*2 表示放大两倍,如果是/2表示缩小两倍

`"crop=320:240:0:0"`视频裁剪,crop=width:height : x : y,其中 width 和 height 表示裁剪后的尺寸,x:y 表示裁剪区域的左上角坐标

还有很多filter可以使用,并且可以实现自定义filter。

原文链接

本文《FFmpeg Filter简单使用》版权归音视频开发老舅所有,引用FFmpeg Filter简单使用需遵循CC 4.0 BY-SA版权协议。


推荐阅读
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文介绍了Perl的测试框架Test::Base,它是一个数据驱动的测试框架,可以自动进行单元测试,省去手工编写测试程序的麻烦。与Test::More完全兼容,使用方法简单。以plural函数为例,展示了Test::Base的使用方法。 ... [详细]
  • 本文介绍了UVALive6575题目Odd and Even Zeroes的解法,使用了数位dp和找规律的方法。阶乘的定义和性质被介绍,并给出了一些例子。其中,部分阶乘的尾零个数为奇数,部分为偶数。 ... [详细]
  • 也就是|小窗_卷积的特征提取与参数计算
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了卷积的特征提取与参数计算相关的知识,希望对你有一定的参考价值。Dense和Conv2D根本区别在于,Den ... [详细]
  • 本文介绍了一个题目的解法,通过二分答案来解决问题,但困难在于如何进行检查。文章提供了一种逃逸方式,通过移动最慢的宿管来锁门时跑到更居中的位置,从而使所有合格的寝室都居中。文章还提到可以分开判断两边的情况,并使用前缀和的方式来求出在任意时刻能够到达宿管即将锁门的寝室的人数。最后,文章提到可以改成O(n)的直接枚举来解决问题。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 纠正网上的错误:自定义一个类叫java.lang.System/String的方法
    本文纠正了网上关于自定义一个类叫java.lang.System/String的错误答案,并详细解释了为什么这种方法是错误的。作者指出,虽然双亲委托机制确实可以阻止自定义的System类被加载,但通过自定义一个特殊的类加载器,可以绕过双亲委托机制,达到自定义System类的目的。作者呼吁读者对网上的内容持怀疑态度,并带着问题来阅读文章。 ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • ***byte(字节)根据长度转成kb(千字节)和mb(兆字节)**parambytes*return*publicstaticStringbytes2kb(longbytes){ ... [详细]
author-avatar
大果粒和小果粒
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有