最简单的基于 FFmpeg 的 AVfilter 例子(水印叠加)

最简单的基于 FFmpeg 的 AVfilter 例子(水印叠加)

  • 最简单的基于 SDL2 的音频播放器
    • 正文
    • 工程文件下载

参考雷霄骅博士的文章,链接:最简单的基于FFmpeg的AVfilter例子(水印叠加)

最简单的基于 SDL2 的音频播放器

正文

FFmpeg 中有一个类库:libavfilter。该类库提供了各种视音频过滤器,有很多现成的 filter 供使用,完成视频的处理很方便。

该例子完成了一个水印叠加的功能。可以将一张透明背景的 png 图片(my_logo.png)作为水印叠加到一个视频文件上。需要注意的是,其叠加工作是在解码后的 YUV 像素数据的基础上完成的。

程序支持使用 SDL1.2 显示叠加后的 YUV 数据,也可以将叠加后的 YUV 输出成文件。

SDL1.2 库的免费下载链接:SDL1.2 - from 雷霄骅.zip

流程图:

请添加图片描述

上面是一张使用 FFmpeg 的 libavfilter 的流程图。可以看出使用 libavfilter 还是需要做不少的初始化工作的。但是使用的时候还是比较简单的,就两个重要的函数:av_buffersrc_add_frame() 和 av_buffersink_get_buffer_ref()。

注:这张图中只列出了和 libavfilter 有关的函数和结构体。代码中其它函数可以参考雷霄骅博士的另一篇文章:100行代码实现最简单的基于FFMPEG+SDL的视频播放器(SDL1.x)

源代码:

// Simplest FFmpeg AVfilter Example.cpp : 定义控制台应用程序的入口点。


/**
* 最简单的基于 FFmpeg 的 AVFilter 例子(叠加水印)
* Simplest FFmpeg AVfilter Example (Watermark)
*
* 源程序:
* 雷霄骅 Lei Xiaohua
* leixiaohua1020@126.com
* 中国传媒大学/数字电视技术
* Communication University of China / Digital TV Technology
* http://blog.csdn.net/leixiaohua1020
*
* 修改:
* 刘文晨 Liu Wenchen
* 812288728@qq.com
* 电子科技大学/电子信息
* University of Electronic Science and Technology of China / Electronic and Information Science
* https://blog.csdn.net/ProgramNovice
*
* 本程序使用 FFmpeg 的 AVfilter 实现了视频的水印叠加功能。
* 可以将一张 PNG 图片作为水印叠加到视频上。
* 是最简单的 FFmpeg 的 AVFilter 方面的教程。
* 适合 FFmpeg 的初学者。
*
* This software uses FFmpeg's AVFilter to add watermark in a video file.
* It can add a PNG format picture as watermark to a video file.
* It's the simplest example based on FFmpeg's AVFilter.
* Suitable for beginner of FFmpeg
*
*/

#include "stdafx.h"

#include <stdio.h>
#include <stdlib.h>

// 解决报错:无法解析的外部符号 __imp__fprintf,该符号在函数 _ShowError 中被引用
#pragma comment(lib, "legacy_stdio_definitions.lib")
extern "C"
{
	// 解决报错:无法解析的外部符号 __imp____iob_func,该符号在函数 _ShowError 中被引用
	FILE __iob_func[3] = { *stdin, *stdout, *stderr };
}

#define __STDC_CONSTANT_MACROS
#ifdef _WIN32
// Windows
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavfilter/avfiltergraph.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/avutil.h"
#include "libswscale/swscale.h"
#include "SDL/SDL.h"
};
#else
// Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavfilter/avfiltergraph.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/avutil.h>
#include <libswscale/swscale.h>
#include <SDL/SDL.h>
#ifdef __cplusplus
};
#endif
#endif

const char *filter_descr = "movie=logo.png[wm];[in][wm]overlay=5:5[out]";

static AVFormatContext *pFormatCtx;
static AVCodecContext *pCodecCtx;

AVFilterContext *buffersrc_ctx;
AVFilterContext *buffersink_ctx;
AVFilterGraph *filter_graph;

static int video_stream_index = -1;


static int open_input_file(const char *filename)
{
	int ret = 1;
	AVCodec *dec;

	if ((ret = avformat_open_input(&pFormatCtx, filename, NULL, NULL)) < 0)
	{
		printf("Can't open input file.\n");
		return ret;
	}
	if ((ret = avformat_find_stream_info(pFormatCtx, NULL)) < 0)
	{
		printf("Can't find stream information.\n");
	}

	// select the video stream
	ret = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
	if (ret < 0)
	{
		printf("Can't find a video stream in the input file.\n");
		return ret;
	}
	video_stream_index = ret;
	pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;

	// init the video decoder
	if ((ret = avcodec_open2(pCodecCtx, dec, NULL)) < 0)
	{
		printf("Can't open video decoder.\n");
		return ret;
	}

	return 0;
}

// 功能:创建配置一个滤镜图,在后续滤镜处理中,可以往此滤镜图输入数据并从滤镜图获得输出数据
static int init_filters(const char *filters_descr)
{
	// // args 是 buffersrc 滤镜的参数
	char args[512];
	int ret;

	AVFilter *buffersrc = avfilter_get_by_name("buffer");
	AVFilter *buffersink = avfilter_get_by_name("ffbuffersink");
	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;

	filter_graph = avfilter_graph_alloc();

	// 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",
		pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
		pCodecCtx->time_base.num, pCodecCtx->time_base.den,
		pCodecCtx->sample_aspect_ratio.num, pCodecCtx->sample_aspect_ratio.den);

	// create and add a filter instance into an existing graph
	ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
		args, NULL, filter_graph);
	if (ret < 0)
	{
		printf("Can't create buffer source.\n");
		return ret;
	}

	// buffer video sink: to terminate the filter chain
	buffersink_params = av_buffersink_params_alloc();
	buffersink_params->pixel_fmts = pix_fmts;
	ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
		NULL, buffersink_params, filter_graph);
	av_free(buffersink_params);
	if (ret < 0)
	{
		printf("Can't create buffer sink.\n");
		return ret;
	}

	// endpoints for the filter graph
	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;

	// add a graph described by a string to a graph
	ret = avfilter_graph_parse_ptr(filter_graph, filters_descr, &inputs, &outputs, NULL);
	if (ret < 0)
	{
		return ret;
	}

	// check validity and configure all the links and formats in the graph
	ret = avfilter_graph_config(filter_graph, NULL);
	if (ret < 0)
	{
		return ret;
	}

	return 0;
}

int main(int argc, char* argv[])
{

	int ret;
	AVPacket packet;
	AVFrame *pFrame;
	AVFrame *pFrame_out;

	int got_frame;
	int frame_cnt;

	av_register_all();
	avfilter_register_all();

	ret = open_input_file("cuc_ieschool.flv");
	if (ret < 0)
	{
		goto end;
	}

	ret = init_filters(filter_descr);
	if (ret < 0)
	{
		goto end;
	}

	FILE *fp_yuv = fopen("test.yuv", "wb+");

	// 帧计数器
	frame_cnt = 0;

	// ---------------------------- SDL 1.2 ----------------------------
	SDL_Surface *screen;
	SDL_Overlay *bmp;
	SDL_Rect rect;

	// 初始化 SDL 系统
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER))
	{
		printf("Could not initialize SDL - %s\n", SDL_GetError());
		return -1;
	}
	screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0);
	if (!screen)
	{
		printf("SDL: could not set video mode - exiting.\n");
		return -1;
	}
	bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height, SDL_YV12_OVERLAY, screen);

	SDL_WM_SetCaption("Simplest FFmpeg Video Filter", NULL);
	// ---------------------------- SDL End ----------------------------

	pFrame = av_frame_alloc();
	pFrame_out = av_frame_alloc();

	// read all packets
	while (1)
	{
		if ((ret = av_read_frame(pFormatCtx, &packet)) < 0)
		{
			break;
		}
		if (packet.stream_index == video_stream_index)
		{
			got_frame = 0;
			ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_frame, &packet);
			if (ret < 0)
			{
				printf("Decode Error.\n");
				return -1;
			}
			if (got_frame)
			{
				pFrame->pts = av_frame_get_best_effort_timestamp(pFrame);

				// push the decoded frame into the filtergraph
				if (av_buffersrc_add_frame(buffersrc_ctx, pFrame) < 0)
				{
					printf("Error while feeding the filtergraph.\n");
					break;
				}

				// pull filtered pictures from the filtergraph
				while (1)
				{
					// get a frame with filtered data from sink and put it in frame
					ret = av_buffersink_get_frame(buffersink_ctx, pFrame_out);
					if (ret < 0)
					{
						break;
					}

					printf("Process %d frame.\n", frame_cnt);

					if (pFrame_out->format == AV_PIX_FMT_YUV420P)
					{
						// Y, U, V
						for (int i = 0; i < pFrame_out->height; i++)
						{
							fwrite(pFrame_out->data[0] + pFrame_out->linesize[0] * i, 1, pFrame_out->width, fp_yuv);
						}
						for (int i = 0; i < pFrame_out->height / 2; i++)
						{
							fwrite(pFrame_out->data[1] + pFrame_out->linesize[1] * i, 1, pFrame_out->width / 2, fp_yuv);
						}
						for (int i = 0; i < pFrame_out->height / 2; i++)
						{
							fwrite(pFrame_out->data[2] + pFrame_out->linesize[2] * i, 1, pFrame_out->width / 2, fp_yuv);
						}

						SDL_LockYUVOverlay(bmp);
						int y_size = pFrame_out->width*pFrame_out->height;
						memcpy(bmp->pixels[0], pFrame_out->data[0], y_size); // Y
						memcpy(bmp->pixels[2], pFrame_out->data[1], y_size / 4); // U
						memcpy(bmp->pixels[1], pFrame_out->data[2], y_size / 4); // V 
						bmp->pitches[0] = pFrame_out->linesize[0];
						bmp->pitches[2] = pFrame_out->linesize[1];
						bmp->pitches[1] = pFrame_out->linesize[2];
						SDL_UnlockYUVOverlay(bmp);
						rect.x = 0;
						rect.y = 0;
						rect.w = pFrame_out->width;
						rect.h = pFrame_out->height;
						SDL_DisplayYUVOverlay(bmp, &rect);
						// Delay 40ms
						SDL_Delay(40);

						frame_cnt++;
					}
					av_frame_unref(pFrame_out);
				}
			}
			av_frame_unref(pFrame);
		}
		av_free_packet(&packet);
	}

	fclose(fp_yuv);

end:
	avfilter_graph_free(&filter_graph);
	if (pCodecCtx != NULL)
	{
		avcodec_close(pCodecCtx);
	}
	avformat_close_input(&pFormatCtx);

	if (ret < 0 && ret != AVERROR_EOF)
	{
		char buf[1024];
		av_strerror(ret, buf, sizeof(buf));
		printf("Error occurred: %s.\n", buf);
		return -1;
	}

	system("pause");
	return 0;
}

本程序可以直接在 Visual Studio 2015 上运行。

程序运行后,可以看到解码的 YUV420 画面,已经在左上角打上了 my_loog.png 水印。

程序输出:

在这里插入图片描述

工程文件下载

GitHub:UestcXiye / Simplest FFmpeg AVfilter Example

CSDN:Simplest FFmpeg AVfilter Example.zip

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/371225.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

sqli.labs靶场(41-53关)

41、第四十一关 -1 union select 1,2,3-- -1 union select 1,database(),(select group_concat(table_name) from information_schema.tables where table_schemadatabase()) -- -1 union select 1,2,(select group_concat(column_name) from information_schema.columns wher…

【HarmonyOS应用开发】HTTP数据请求(十四)

文章末尾含相关内容源代码 一、概述 日常生活中我们使用应用程序看新闻、发送消息等&#xff0c;都需要连接到互联网&#xff0c;从服务端获取数据。例如&#xff0c;新闻应用可以从新闻服务器中获取最新的热点新闻&#xff0c;从而给用户打造更加丰富、更加实用的体验。 那么…

http伪造本地用户字段系列总结

本篇记录了http伪造本地用户的多条字段&#xff0c;便于快速解决题目 用法举例&#xff1a; 直接把伪造本地用户的多个字段复制到请求头中&#xff0c;光速解决部分字段被过滤的问题。 Client-IP: 127.0.0.1 Forwarded-For-Ip: 127.0.0.1 Forwarded-For: 127.0.0.1 Forwarded…

[技术杂谈]如何下载vscode历史版本

网站模板&#xff1a; https://code.visualstudio.com/updates/v1_85 如果你想下载1.84系列可以访问https://code.visualstudio.com/updates/v1_84​​​​​​ 然后看到&#xff1a; 选择对应版本下载即可&#xff0c;我是windows x64系统选择x64即可开始下载

Python基础知识:Python流程控制语句

流程控制就是控制程序如何执行的方法&#xff0c;适用于任何一门编程语言&#xff0c;其作用在于&#xff0c;可以根据用户的需求决定程序执行的顺序。计算机在运行程序时&#xff0c;有3种执行方法&#xff0c;第一种是顺序执行&#xff0c;自上而下顺序执行所有的语句&#x…

python爬虫代码示例:爬取京东详情页图片【京东API接口】

一、Requests请求示例【京东API接口】 爬虫爬取网页内容首先要获取网页的内容&#xff0c;通过requests库进行获取。 安装 pip install requests 示例代码 import requests url "http://store.weigou365.cn"res requests.get(url)res.text 执行效果如下&#x…

我在项目中使用Redis的几个场景

目录 缓存 会话存储 分布式锁 消息队列 位统计 计数器 排行榜 缓存 缓存的目的是为了提高系统响应速度、减少数据库等资源的压力&#xff0c;redis作为键值对形式的内存数 据库&#xff0c;可以提供非常快速的读取速度&#xff0c;使得它成为存储热点数据或频繁访问数…

MiniCPM:揭示端侧大语言模型的无限潜力

技术博客链接&#xff1a; &#x1f517;https://shengdinghu.notion.site/MiniCPM ➤ Github地址&#xff1a; &#x1f517;https://github.com/OpenBMB/MiniCPM ➤ Hugging Face地址&#xff1a; &#x1f517;https://huggingface.co/openbmb/MiniCPM-2B-sft-bf16 1 …

3D Line Mapping Revisited论文阅读

1. 代码地址 GitHub - cvg/limap: A toolbox for mapping and localization with line features. 2. 项目主页 3D Line Mapping Revisited 3. 摘要 提出了一种基于线的重建算法&#xff0c;Limap&#xff0c;可以从多视图图像中构建3D线地图&#xff0c;通过线三角化、精心…

随机森林超参数的网格优化(机器学习的精华--调参)

随机森林超参数的网格优化&#xff08;机器学习的精华–调参&#xff09; 随机森林各个参数对算法的影响 影响力参数⭐⭐⭐⭐⭐几乎总是具有巨大影响力n_estimators&#xff08;整体学习能力&#xff09;max_depth&#xff08;粗剪枝&#xff09;max_features&#xff08;随机…

ACM训练题:Fadi and LCM

首先LCM&#xff08;a&#xff0c;b&#xff09;X&#xff0c;说明a*b>X&#xff0c;当且仅当a&#xff0c;b互质时相等&#xff0c;题意要让a&#xff0c;b都尽可能小&#xff0c;最好让a*bX&#xff0c;即a&#xff0c;b互质。原因如下&#xff1a; 最小公倍数由a、b中最…

电脑上常见的绘图软件有哪些?

现在在电脑上绘图很流行&#xff0c;不仅可以随时更改&#xff0c;还可以提高绘图效率&#xff0c;绘图软件中有很多工具。市场上的计算机绘图软件种类繁多。包括艺术设计、工业绘图和3D绘图。那么每个绘图软件都有自己的特点。那么&#xff0c;哪个更适合计算机绘画软件呢&…

Redis核心技术与实战【学习笔记】 - 22.浅谈Redis的ACID相关知识

概述 事务是数据库的一个重要功能。所谓的事务&#xff0c;就是指对数据进行读写的一系列操作。事务在执行时&#xff0c;会提供专门的属性保证&#xff0c;包括原子性&#xff08;Atomicity&#xff09;、一致性&#xff08;Consistency&#xff09;、隔离性&#xff08;Isol…

Android电动汽车充电服务vue+uniAPP微信小程序

本系统利用SSM和Uniapp技术进行开发电动汽车充电服务系统是未来的趋势。该系统使用的编程语言是Java&#xff0c;数据库采用的是MySQL数据库&#xff0c;基本完成了系统设定的目标&#xff0c;建立起了一个较为完整的系统。建立的电动汽车充电服务系统用户使用浏览器就可以对其…

centos 7.7 离线安装docker

centos 7.7 离线安装docker Index of linux/static/stable/x86_64/https://download.docker.com/linux/static/stable/x86_64/ 【1】离线下载docker 压缩包上传至 /usr/local 目录&#xff0c;解压缩&#xff0c;并复制到 /usr/bin/ 目录中。 cd /usr/local/tar -zxvf docke…

一篇文章了解区分指针数组,数组指针,函数指针,链表。

最近在学习指针&#xff0c;发现指针有这许多的知识&#xff0c;其中的奥妙还很多&#xff0c;需要学习的也很多&#xff0c;今天那我就将标题中的有关指针知识&#xff0c;即指针数组&#xff0c;数组指针&#xff0c;函数指针&#xff0c;给捋清楚这些知识点&#xff0c;区分…

两次NAT

两次NAT即Twice NAT&#xff0c;指源IP和目的IP同时转换&#xff0c;该技术应用于内部网络主机地址与外部网络上主机地址重叠的情况。 如图所示&#xff0c;两次NAT转换的过程如下: 内网Host A要访问地址重叠的外部网络Host B&#xff0c;Host A向位于外部网络的DNS服务器发送…

瑞_23种设计模式_建造者模式

文章目录 1 建造者模式&#xff08;Builder Pattern&#xff09;1.1 介绍1.2 概述1.3 创作者模式的结构 2 案例一2.1 需求2.2 代码实现 3 案例二3.1 需求3.2 代码实现 4 模式拓展 ★★★4.1 重构前4.2 重构后 5 总结5.1 建造者模式优缺点5.2 建造者模式使用场景5.3 建造者模式 …

使用SPM_batch进行批量跑脚本(matlab.m)

软件&#xff1a;spm8matlab2023bwin11 数据格式&#xff1a; F:\ASL\HC\CBF\HC_caishaoqing\CBF.nii F:\ASL\HC\CBF\HC_caishaoqing\T1.nii F:\ASL\HC\CBF\HC_wangdonga\CBF.nii F:\ASL\HC\CBF\HC_wangdonga\T1.nii clear spmdirD:\AnalysisApps\spm8; datadirF:\ASL\HC\CBF…

Haas 开发板连接阿里云上传温湿度和电池电压

目录 一、在阿里云上创建一个产品 二、开发环境的介绍 三、创建wifi示例 四、编写SI7006和ADC驱动 五、wifi配网 六、主要源码 七、查看实现结果 一、在阿里云上创建一个产品 登录自己的阿里云账号&#xff0c; 应该支付宝&#xff0c;淘宝账号都是可以的。 接着根据需求…
最新文章