ffmpeg用filter实现视频scale

1、概述

此例子用ffmpeg的filter实现视频scale。

2、代码

/**
 * 最简单的基于FFmpeg的AVFilter例子(scale)
 *
 * 缪国凯(MK)
 * [email protected]
 *
 * http://blog.csdn.net/dancing_night
 *
 * 本程序使用FFmpeg的AVfilter实现了视频的缩放功能。
 *
 *
 */

#include "stdafx.h"

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

#pragma comment(lib, "avcodec.lib")
#pragma comment(lib, "avformat.lib")
#pragma comment(lib, "avutil.lib")
#pragma comment(lib, "avdevice.lib")
#pragma comment(lib, "avfilter.lib")

//#pragma comment(lib, "avfilter.lib")
//#pragma comment(lib, "postproc.lib")
//#pragma comment(lib, "swresample.lib")
#pragma comment(lib, "swscale.lib")

static AVFormatContext *ifmt_ctx, *ofmt_ctx;
static AVCodecContext *pCodecCtx;
AVFilterContext *buffersink_ctx;
AVFilterContext *buffersrc_ctx;
AVFilterGraph *filter_graph;
static int video_stream_index = -1;
static int64_t last_pts = AV_NOPTS_VALUE;

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

	if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
		printf( "Cannot open input file\n");
		return ret;
	}

	if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
		printf( "Cannot find stream information\n");
		return ret;
	}

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

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

	return 0;
}

int openoutputfile(const char* filename, int width, int height)
{
	AVStream *out_stream;
	int ret = 0;
	if ((ret = avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, filename)) < 0)
	{
		printf("can not alloc output context");
		return ret;
	}
	for (int i = 0; i < ifmt_ctx->nb_streams; i++)
	{
		//if the stream is video stream then find the encoder default
		//and set context and open the encoder
		if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			out_stream = NULL;
			//new a stream
			out_stream = avformat_new_stream(ofmt_ctx, NULL);
			if (!out_stream)
			{
				printf("can not new stream for output");
				return AVERROR_UNKNOWN;
			}

			//use default video encoder
			out_stream->codec->codec = avcodec_find_encoder(ofmt_ctx->oformat->video_codec);

			out_stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
			out_stream->codec->pix_fmt = PIX_FMT_YUV420P;
			out_stream->codec->width = width;
			out_stream->codec->height = height;
			out_stream->codec->time_base.num = 1;
			out_stream->codec->time_base.den = 25;
			out_stream->codec->bit_rate = 400000;
			out_stream->codec->gop_size=250;
			//H264
			out_stream->codec->qmin = 10;
			out_stream->codec->qmax = 40;
			//Optional Param
			out_stream->codec->max_b_frames=3;

			AVDictionary *param = NULL;
			if (out_stream->codec->codec->id == AV_CODEC_ID_H264)
			{
				av_dict_set(¶m, "preset", "slow", 0);
				av_dict_set(¶m, "tune", "zerolatency", 0);
				av_dict_set(¶m, "profile", "main", 0);
			}

			//open encoder
			ret = avcodec_open2(out_stream->codec, out_stream->codec->codec, ¶m);

			if (ret < 0)
			{
				printf("can not open encoder");
				return ret;
			}

			if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
				out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;

			break;
		}
	}

	//dump output info
	av_dump_format(ofmt_ctx, 0, filename, 1);

	//open the output file handle
	if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
	{
		ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
		if (ret < 0)
		{
			printf("can not open the output file handle");
			return ret;
		}
	}

	//write output file header
	if ((ret = avformat_write_header(ofmt_ctx, NULL)) < 0)
	{
		printf("can not write output file header");
		return ret;
	}

	return 0;
}

static int init_filters(const char *filters_descr)
{
	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 PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, 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);

	ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
		args, NULL, filter_graph);
	if (ret < 0) {
		printf("Cannot 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("Cannot 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;

	if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
		&inputs, &outputs, NULL)) < 0)
		return ret;

	if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
		return ret;
	return 0;
}

static int encode_write_video_frame(AVFrame *filt_frame, int *got_frame)
{
	int ret;
	int got_frame_local;
	AVPacket enc_pkt;
	unsigned int stream_index = 0;
	if (!got_frame)
		got_frame = &got_frame_local;
	av_log(NULL, AV_LOG_INFO, "Encoding frame\n");
	/* encode filtered frame */
	enc_pkt.data = NULL;
	enc_pkt.size = 0;
	av_init_packet(&enc_pkt);
	ret = avcodec_encode_video2(ofmt_ctx->streams[stream_index]->codec, &enc_pkt,
		filt_frame, got_frame);
	av_frame_free(&filt_frame);
	if (ret < 0)
		return ret;
	if (!(*got_frame))
		return 0;
	/* prepare packet for muxing */
	enc_pkt.stream_index = stream_index;
	enc_pkt.dts = av_rescale_q_rnd(enc_pkt.dts,
		ofmt_ctx->streams[stream_index]->codec->time_base,
		ofmt_ctx->streams[stream_index]->time_base,
		(AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
	enc_pkt.pts = av_rescale_q_rnd(enc_pkt.pts,
		ofmt_ctx->streams[stream_index]->codec->time_base,
		ofmt_ctx->streams[stream_index]->time_base,
		(AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
	enc_pkt.duration = av_rescale_q(enc_pkt.duration,
		ofmt_ctx->streams[stream_index]->codec->time_base,
		ofmt_ctx->streams[stream_index]->time_base);
	av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
	/* mux encoded frame */
	ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
	return ret;
}

static int filter_encode_write_video_frame(AVFrame *frame)
{
    int ret;
    AVFrame *filt_frame;
    av_log(NULL, AV_LOG_INFO, "Pushing decoded frame to filters\n");
    /* push the decoded frame into the filtergraph */
    ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
            frame, 0);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
        return ret;
    }
    /* pull filtered frames from the filtergraph */
    while (1) {
        filt_frame = av_frame_alloc();
        if (!filt_frame) {
            ret = AVERROR(ENOMEM);
            break;
        }
        av_log(NULL, AV_LOG_INFO, "Pulling filtered frame from filters\n");
        ret = av_buffersink_get_frame(buffersink_ctx,
                filt_frame);
        if (ret < 0) {
            /* if no more frames for output - returns AVERROR(EAGAIN)
             * if flushed and no more frames for output - returns AVERROR_EOF
             * rewrite retcode to 0 to show it as normal procedure completion
             */
            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                ret = 0;
            av_frame_free(&filt_frame);
            break;
        }
        filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
        ret = encode_write_video_frame(filt_frame, NULL);
        if (ret < 0)
            break;
    }
    return ret;
}

int flush_encoder(AVFormatContext *fmt_ctx,unsigned int stream_index)
{
	int ret;
	int got_frame;
	if (!(ofmt_ctx->streams[stream_index]->codec->codec->capabilities &
		CODEC_CAP_DELAY))
		return 0;
	while (1) {
		av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", stream_index);
		ret = encode_write_video_frame(NULL, &got_frame);
		if (ret < 0)
			break;
		if (!got_frame)
			return 0;
	}
	return ret;
}

int _tmain(int argc, _TCHAR* argv[])
{
	char filter_descr[100]/* = "movie=my_logo.png[wm];[in][wm]overlay=5:5[out]"*/;
	AVPacket pkt_in, pkt_out;
	unsigned int stream_index;
	int ret;
	AVPacket packet;
	AVFrame *frame;
	int got_frame;
	int width, height;
	width = 400;
	height = 300;

	sprintf(filter_descr, "[in]scale=%d:%d[out]", width, height);

	avcodec_register_all();
	av_register_all();
	avfilter_register_all();

	if ((ret = open_input_file("test.mp4")) < 0)
		goto end;
	if ((ret = init_filters(filter_descr)) < 0)
		goto end;
	if ((ret = openoutputfile("test_scale.mp4", width, height)) < 0)
		goto end;

	// to be add
	while(1)
	{
		if (av_read_frame(ifmt_ctx, &pkt_in) < 0)
		{
			break;
		}
		pkt_out.data = NULL;
		pkt_out.size = 0;
		av_init_packet(&pkt_out);
		stream_index = pkt_in.stream_index;
		frame = av_frame_alloc();
		int got_frame = -1;
		int ret = -1;

		//calculate the pts and dts
		pkt_in.dts = av_rescale_q_rnd(pkt_in.dts,
			ifmt_ctx->streams[stream_index]->time_base,
			ifmt_ctx->streams[stream_index]->codec->time_base,
			(AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
		pkt_in.pts = av_rescale_q_rnd(pkt_in.pts,
			ifmt_ctx->streams[stream_index]->time_base,
			ifmt_ctx->streams[stream_index]->codec->time_base,
			(AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));

		if (ifmt_ctx->streams[stream_index]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			ret = avcodec_decode_video2(ifmt_ctx->streams[stream_index]->codec, frame, &got_frame, &pkt_in);
			if (ret < 0)
			{
				av_frame_free(&frame);
				printf("decoding video stream failed\n");
				break;
			}

			if (got_frame)
			{
				frame->pts = av_frame_get_best_effort_timestamp(frame);
				ret = filter_encode_write_video_frame(frame);
				av_frame_free(&frame);
				if (ret < 0)
					goto end;
			}

		}
	}

	//Flush Encoder
	ret = flush_encoder(ofmt_ctx,0);
	if (ret < 0) {
		printf("Flushing encoder failed\n");
		return -1;
	}

	av_write_trailer(ofmt_ctx);

end:
	avfilter_graph_free(&filter_graph);
	if (pCodecCtx)
		avcodec_close(pCodecCtx);
	avformat_close_input(&ifmt_ctx);

	if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
	{
		for (int i = 0; i < ofmt_ctx->nb_streams; i++)
		{
			if (ofmt_ctx->streams[i]->codec)
			{
				avcodec_close(ofmt_ctx->streams[i]->codec);
			}
		}

		avio_close(ofmt_ctx->pb);
	}
	avformat_free_context(ofmt_ctx);

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

	return 0;
}

3、解释

简单说下流程:open input->open output->init filter -> read packet -> decode frame -> push into filter -> pull from filter -> encode -> write into file

4、工程下载

http://download.csdn.net/detail/dancing_night/9066603

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-14 10:53:12

ffmpeg用filter实现视频scale的相关文章

利用FFmpeg玩转Android视频录制与压缩(二)&lt;转&gt;

转载出处:http://blog.csdn.net/mabeijianxi/article/details/72983362 预热 时光荏苒,光阴如梭,离上一次吹牛逼已经过去了两三个月,身边很多人的女票已经分了又合,合了又分,本屌依旧骄傲单身.上一次啊我们大致说了一些简单的FFmpeg命令以及Java层简单的调用方式,然后有很多朋友在github或者csdn上给我留言,很多时候我都选择避而不答,原因是本库以前用的so包是不开源的,我根本改不了里面东西.但是这一次啊我们玩点大的,我重新编译了FFm

ffmpeg 命令行改变视频分辨率

视频:ffmpeg -i input.avi -vf scale=320:240 output.avi 图片: ffmpeg -i input.jpg -vf scale=320:240 output_320x240.png 原文地址:https://www.cnblogs.com/nanqiang/p/12103307.html

基于ffmpeg和libvlc的视频剪辑、播放器

以前研究的时候,写过一个简单的基于VLC的视频播放器.后来因为各种项目,有时为了方便测试,等各种原因,陆续加了一些功能,现在集成了视频播放.视频加减速.视频剪切,视频合并(增加中)等功能在一起.有时候看点网上下载的视频,可以一边看,一边能处理视频前后的广告,感觉也还可以用,就想把它开源出去,一方面希望有需要的朋友可以参考.借鉴,另一方面也希望可以促进它进一步的丰富功能,最终能实现一款简单又够用的视频剪辑软件. 程序框架 先上一张程序截图 基本上讲,它的播放功能是基于VLC,剪辑功能是基于FFmp

FFmpeg滤镜实现区域视频增强 及 D3D实现视频播放区的拉大缩小

1.区域视频增强 FFmpeg滤镜功能十分强大,用滤镜可以实现视频的区域增强功能. 用eq滤镜就可以实现亮度.对比度.饱和度等的常用视频增强功能. 推荐两篇写得不错的博文: (1)ffmpeg综合应用示例(二)——为直播流添加特效 - 张晖的专栏 - 博客频道 - CSDN.NET: (2)ffmpeg 滤镜及其效果 - 党玉涛 - 博客频道 - CSDN.NET 第(1)篇博客对于如何用代码来写滤镜讲得比较清楚,第(2)篇则列出了许多滤镜写法的例子. 参考第(1)篇博客,滤镜的代码如下: 设置

ffmpeg一些filter用法、以及一些功能命令

1.加字幕 命令:ffmpeg -i <input> -filter_complex subtitles=filename=<SubtitleName>-y <output> 说明:利用libass来为视频嵌入字幕,字幕是直接嵌入到视频里的硬字幕. 参考资料:http://ffmpeg.org/ffmpeg-filters.html#subtitles-1 2.剪切 命令:ffmpeg -i <input>-ss 0 -t 10 -y <output&

ASP.NET下调用ffmpeg与mencoder实现视频转换截屏

最近要做一个视频播放的系统,用到了ffmpeg和mencoder两个工具,查了一些资料,发现这方面的资料还挺多的,但是就是乱了一点,我自己从头整理了一下,和大家分享一下: 1.ffmpeg实现视频(avi,wmv等格式)转换为flv格式: /// <summary> /// 转换视频为flv /// </summary> /// <param name="fileName">上传视频文件的路径(原文件)</param> /// <p

FFmpeg: 最好的音视频处理工具(翻译)

FFmpeg: The ultimate Video and Audio Manipulation Tool(原标题) What is FFmpeg? Chances are you've probably heard of FFmpeg already. It's a set of tools dedicated to decoding, encoding and transcoding video and audio. FFmpeg is based on the popular libav

ffmpeg调整缩放裁剪视频的基础

1. resize and scale video 调整视频的大小和尺寸 1-1.调整视频大小(resize)是改变视频的宽度和高度. 使用-s参数实现,语法:ffmpeg  -i  input_file  -s  wxh  output_file (wxh是宽x高,比如320x240)  调整视频的尺寸(scale)是改变帧的数量. 1-2.预定义的视频大小简写如下: 2.

基于最简单的FFmpeg包封过程:视频和音频分配器启动(demuxer-simple)

===================================================== 基于最简单的FFmpeg封装工艺的系列文章上市: 最简单的基于FFmpeg的封装格式处理:视音频分离器简化版(demuxer-simple) 最简单的基于FFmpeg的封装格式处理:视音频分离器(demuxer) 最简单的基于FFmpeg的封装格式处理:视音频复用器(muxer) 最简单的基于FFMPEG的封装格式处理:封装格式转换(remuxer) ===================