FFmpeg 使用overlay位AVFrame中添加水印的AVFrame的完整代码
时间: 2023-03-23 15:01:41 浏览: 172
ffmpeg-水印(第一章资源)-android环境调用ffmpeg的demo
以下是使用FFmpeg在AVFrame中添加水印的完整示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <math.h>
#include <stdint.h>
#include <libavutil/imgutils.h>
#include <libavutil/parseutils.h>
#include <libavutil/pixdesc.h>
#include <libavutil/opt.h>
#include <libavutil/timestamp.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
int main(int argc, char **argv) {
const char *input_filename = "input.mp4";
const char *output_filename = "output.mp4";
const char *watermark_filename = "watermark.png";
AVFormatContext *input_fmt_ctx = NULL, *output_fmt_ctx = NULL;
AVCodecContext *video_dec_ctx = NULL, *video_enc_ctx = NULL;
AVCodec *video_codec = NULL;
AVStream *video_stream = NULL, *output_video_stream = NULL;
AVFrame *frame = NULL, *watermark_frame = NULL;
AVPacket pkt;
int video_stream_idx = -1, ret, frame_count = 0;
// Open input file
if ((ret = avformat_open_input(&input_fmt_ctx, input_filename, NULL, NULL)) < 0) {
fprintf(stderr, "Could not open input file '%s' (error '%s')\n", input_filename, av_err2str(ret));
return 1;
}
// Retrieve stream information
if ((ret = avformat_find_stream_info(input_fmt_ctx, NULL)) < 0) {
fprintf(stderr, "Could not find stream information (error '%s')\n", av_err2str(ret));
goto end;
}
// Find the first video stream
for (int i = 0; i < input_fmt_ctx->nb_streams; i++) {
AVStream *stream = input_fmt_ctx->streams[i];
AVCodecParameters *codecpar = stream->codecpar;
if (codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream_idx = i;
break;
}
}
if (video_stream_idx == -1) {
fprintf(stderr, "Could not find a video stream\n");
goto end;
}
// Allocate a video stream in the output context
output_fmt_ctx = avformat_alloc_context();
if (!output_fmt_ctx) {
fprintf(stderr, "Could not allocate output context\n");
goto end;
}
// Copy the input format to the output format
if ((ret = avformat_copy_context(output_fmt_ctx, input_fmt_ctx)) < 0) {
fprintf(stderr, "Could not copy input format to output format (error '%s')\n", av_err2str(ret));
goto end;
}
// Open the output file
if ((ret = avio_open(&output_fmt_ctx->pb, output_filename, AVIO_FLAG_WRITE)) < 0) {
fprintf(stderr, "Could not open output file '%s' (error '%s')\n", output_filename, av_err2str(ret));
goto end;
}
// Create a new video stream in the output context
video_stream = input_fmt_ctx->streams[video_stream_idx];
video_codec = avcodec_find_decoder(video_stream->codecpar->codec_id);
if (!video_codec) {
fprintf(stderr, "Could not find video codec\n");
goto end;
}
video
阅读全文