FFmpeg C++实现视频水印
时间: 2023-03-20 11:02:54 浏览: 254
ffmpeg 支持水印
3星 · 编辑精心推荐
要在视频中添加水印,可以使用 FFmpeg 库中提供的过滤器来实现。以下是一个基本的 C 代码示例,它使用 FFmpeg 库中的过滤器来将文本水印添加到视频中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libavformat/avformat.h>
#include <libavfilter/avfiltergraph.h>
#include <libavfilter/buffersrc.h>
#include <libavfilter/buffersink.h>
int main(int argc, char **argv) {
AVFilterContext *buffersrc_ctx;
AVFilterContext *buffersink_ctx;
AVFilterGraph *filter_graph;
int ret;
if (argc != 3) {
fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
exit(1);
}
av_register_all();
avfilter_register_all();
AVFormatContext *fmt_ctx = NULL;
ret = avformat_open_input(&fmt_ctx, argv[1], NULL, NULL);
if (ret < 0) {
fprintf(stderr, "Could not open input file '%s'", argv[1]);
exit(1);
}
ret = avformat_find_stream_info(fmt_ctx, NULL);
if (ret < 0) {
fprintf(stderr, "Could not find stream information");
exit(1);
}
av_dump_format(fmt_ctx, 0, argv[1], 0);
AVCodecContext *codec_ctx = NULL;
int video_stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
if (video_stream_index < 0) {
fprintf(stderr, "Could not find video stream in input file");
exit(1);
}
AVStream *video_stream = fmt_ctx->streams[video_stream_index];
codec_ctx = video_stream->codec;
AVCodec *decoder = avcodec_find_decoder(codec_ctx->codec_id);
if (!decoder) {
fprintf(stderr, "Failed to find decoder for stream #%u codec ID %d\n", video_stream_index, codec_ctx->codec_id);
exit(1);
}
ret = avcodec_open2(codec_ctx, decoder, NULL);
if (ret < 0) {
fprintf(stderr, "Failed to open decoder for stream #%u\n", video_stream_index);
exit(1);
}
AVFrame *frame = av_frame_alloc();
AVPacket packet;
av_init_packet(&packet);
filter_graph = avfilter_graph_alloc();
char args[512];
snprintf(args, sizeof(args),
"drawtext=text='My Watermark':x=(w-text_w)/2:y=(h-text_h)/2:fontfile=/usr/share/fonts/truetype/freefont/FreeSerif.ttf:fontsize=48:fontcolor=white");
const AVFilter *buffersrc = avfilter_get_by_name("buffer");
const AVFilter *buffersink = avfilter_get_by_name("buffersink");
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE};
sprintf(args, "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
codec_ctx->width, codec_ctx->height, codec_ctx->pix_fmt,
video_stream->
阅读全文