最简单的基于 FFmpeg 的视频编码器(YUV 编码为 HEVC(H.265))

这篇具有很好参考价值的文章主要介绍了最简单的基于 FFmpeg 的视频编码器(YUV 编码为 HEVC(H.265))。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

最简单的基于 FFmpeg 的视频编码器(YUV 编码为 HEVC(H.265))

参考雷霄骅博士的文章,链接:最简单的基于FFmpeg的视频编码器-更新版(YUV编码为HEVC(H.265))

正文

前一阵子做过一个基于 FFmpeg 的视频编码器的例子:最简单的基于 FFmpeg 的视频编码器(YUV 编码为 H.264)。

在该例子中,可以将 YUV 像素数据(YUV420P)编码为 H.264 码流。因为 FFmpeg 也支持 libx265 ,因此对上述编码 H.264 的例子进行了升级,使之变成编码 H.265(HEVC)的例子。

本文介绍一个最简单的基于 FFmpeg 的视频编码器。

该编码器实现了 YUV420P 的像素数据编码为 H.265(HEVC) 的压缩编码数据。

下面附上一张 FFmpeg 编码视频的流程图。通过该流程,不仅可以编码 H.264/H.265 的码流,而且可以编码 MPEG4/MPEG2/VP9/VP8 等多种码流。实际上使用 FFmpeg 编码视频的方式都是一样的。图中蓝色背景的函数是实际输出数据的函数。浅绿色的函数是视频编码的函数。

ffmpeg hevc,FFmpeg,ffmpeg,音视频,h.265,视频编解码

简单介绍一下流程中各个函数的意义:

  1. av_register_all():注册 FFmpeg 所有编解码器。
  2. avformat_alloc_output_context2():初始化输出码流的 AVFormatContext。
  3. avio_open():打开输出文件。
  4. av_new_stream():创建输出码流的 AVStream。
  5. avcodec_find_encoder():查找编码器。
  6. avcodec_open2():打开编码器。
  7. avformat_write_header():写文件头(对于某些没有文件头的封装格式,不需要此函数。比如说 MPEG2TS)。
  8. avcodec_encode_video2():编码一帧视频。即将 AVFrame(存储 YUV 像素数据)编码为 AVPacket(存储 H.264 等格式的码流数据)。
  9. av_write_frame():将编码后的视频码流写入文件。
  10. flush_encoder():输入的像素数据读取完成后调用此函数。用于输出编码器中剩余的 AVPacket。
  11. av_write_trailer():写文件尾(对于某些没有文件头的封装格式,不需要此函数。比如说 MPEG2TS)。

源代码:

// Simplest FFmpeg Video Encoder H.265.cpp : 定义控制台应用程序的入口点。
//

/**
* 最简单的基于 FFmpeg 的视频编码器
* Simplest FFmpeg Video Encoder
*
* 源程序:
* 雷霄骅 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
*
* 本程序实现了 YUV 像素数据编码为视频码流(HEVC(H.265),H264,MPEG2,VP8 等等)。
* 是最简单的 FFmpeg 视频编码方面的教程。
* 通过学习本例子可以了解 FFmpeg 的编码流程。
*
* This software encode YUV420P data to HEVC(H.265) bitstream (or
* H.264, MPEG2, VP8 etc.).
* It's the simplest video encoding software based on FFmpeg.
* Suitable for beginner of FFmpeg
*
*/

#include "stdafx.h"

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

// 解决报错:fopen() 函数不安全
#pragma warning(disable:4996)

// 解决报错:无法解析的外部符号 __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 "libavutil/opt.h"
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
};
#else
// Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#ifdef __cplusplus
};
#endif
#endif

int flush_encoder(AVFormatContext *fmt_ctx, unsigned int stream_index)
{
	int ret;
	int got_frame;
	AVPacket enc_pkt;

	if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities & CODEC_CAP_DELAY))
	{
		return 0;
	}

	while (1)
	{
		printf("Flushing stream #%u encoder.\n", stream_index);
		enc_pkt.data = NULL;
		enc_pkt.size = 0;
		av_init_packet(&enc_pkt);
		ret = avcodec_encode_video2(fmt_ctx->streams[stream_index]->codec, &enc_pkt,
			NULL, &got_frame);
		av_frame_free(NULL);
		if (ret < 0)
			break;
		if (!got_frame)
		{
			ret = 0;
			break;
		}
		printf("Flush Encoder: Succeed to encode 1 frame! size:%5d.\n", enc_pkt.size);
		// mux encoded frame
		ret = av_write_frame(fmt_ctx, &enc_pkt);
		if (ret < 0)
		{
			break;
		}
	}
	return ret;
}

int main(int argc, char* argv[])
{
	AVFormatContext* pFormatCtx;
	AVOutputFormat* fmt;
	AVStream* video_stream;
	AVCodecContext* pCodecCtx;
	AVCodec* pCodec;

	AVPacket pkt;
	uint8_t* picture_buf;
	AVFrame* pFrame;

	int ret;
	int size = 0;
	int y_size = 0;
	int framecnt = 0;

	// Input raw YUV data 
	FILE *fp_in = fopen("ds_480x272.yuv", "rb");
	// FILE *in_file = fopen("src01_480x272.yuv", "rb");
	const int in_width = 480, in_height = 272; // Input data's width and height
	int framenum = 100; // Frames to encode 

	// Output Filepath 
	// const char* out_file = "ds.h264";
	const char* out_file = "ds.hevc";
	// const char* out_file = "src01.h264";              
	// const char* out_file = "src01.ts";

	av_register_all();

	// Method 1
	// pFormatCtx = avformat_alloc_context();
	// fmt = av_guess_format(NULL, out_file, NULL); // Guess Format
	// pFormatCtx->oformat = fmt;

	// Method 2
	avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
	fmt = pFormatCtx->oformat;

	// Open output URL
	ret = avio_open(&pFormatCtx->pb, out_file, AVIO_FLAG_READ_WRITE);
	if (ret < 0)
	{
		// 输出文件打开失败
		printf("Can't open output file.\n");
		return -1;
	}

	video_stream = avformat_new_stream(pFormatCtx, 0);
	video_stream->time_base.num = 1;
	video_stream->time_base.den = 25;

	if (video_stream == NULL)
	{
		printf("Can't create video stream.\n");
		return -1;
	}

	// Param that must set
	pCodecCtx = video_stream->codec;
	// pCodecCtx->codec_id = AV_CODEC_ID_HEVC;
	pCodecCtx->codec_id = fmt->video_codec;
	pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
	pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
	pCodecCtx->width = in_width;
	pCodecCtx->height = in_height;
	pCodecCtx->bit_rate = 400000;
	pCodecCtx->gop_size = 250;
	pCodecCtx->time_base.num = 1;
	pCodecCtx->time_base.den = 25;
	// H.264
	// pCodecCtx->me_range = 16;
	// pCodecCtx->max_qdiff = 4;
	// pCodecCtx->qcompress = 0.6;
	pCodecCtx->qmin = 10;
	pCodecCtx->qmax = 51;

	// Optional Param
	pCodecCtx->max_b_frames = 3;

	// Set Option
	AVDictionary *param = 0;
	// H.264
	if (pCodecCtx->codec_id == AV_CODEC_ID_H264)
	{
		av_dict_set(&param, "preset", "slow", 0);
		av_dict_set(&param, "tune", "zerolatency", 0);
		// av_dict_set(&param, "profile", "main", 0);
	}
	// H.265
	if (pCodecCtx->codec_id == AV_CODEC_ID_H265)
	{
		av_dict_set(&param, "x265-params", "qp=20", 0);
		av_dict_set(&param, "preset", "ultrafast", 0);
		av_dict_set(&param, "tune", "zero-latency", 0);
	}

	// Show some Information
	av_dump_format(pFormatCtx, 0, out_file, 1);

	pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
	if (!pCodec)
	{
		// 没有找到合适的编码器
		printf("Can't find encoder.\n");
		return -1;
	}

	ret = avcodec_open2(pCodecCtx, pCodec, &param);
	if (ret < 0)
	{
		// 编码器打开失败
		printf("Failed to open encoder.\n");
		return -1;
	}

	pFrame = avcodec_alloc_frame();
	size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
	picture_buf = (uint8_t *)av_malloc(size);
	avpicture_fill((AVPicture *)pFrame, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);

	// Write File Header
	avformat_write_header(pFormatCtx, NULL);

	y_size = pCodecCtx->width * pCodecCtx->height;
	av_new_packet(&pkt, 3 * y_size);

	for (int i = 0; i < framenum; i++)
	{
		// Read raw YUV data
		if (fread(picture_buf, 1, y_size * 3 / 2, fp_in) <= 0)
		{
			// 文件读取错误
			printf("Failed to read raw YUV data.\n");
			return -1;
		}
		else if (feof(fp_in))
		{
			break;
		}

		pFrame->data[0] = picture_buf; // Y
		pFrame->data[1] = picture_buf + y_size; // U 
		pFrame->data[2] = picture_buf + y_size * 5 / 4; // V

		// PTS
		pFrame->pts = i;
		// pFrame->pts = i*(video_stream->time_base.den) / ((video_stream->time_base.num) * 25);

		int got_picture = 0;
		// Encode
		ret = avcodec_encode_video2(pCodecCtx, &pkt, pFrame, &got_picture);
		if (ret < 0)
		{
			printf("Failed to encode! \n");
			return -1;
		}
		if (got_picture == 1)
		{
			printf("Succeed to encode frame: %5d\tsize:%5d.\n", framecnt, pkt.size);
			framecnt++;
			pkt.stream_index = video_stream->index;
			ret = av_write_frame(pFormatCtx, &pkt);
			av_free_packet(&pkt);
		}
	}

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

	// Write file trailer
	av_write_trailer(pFormatCtx);

	// Clean
	if (video_stream)
	{
		avcodec_close(video_stream->codec);
		av_free(pFrame);
		av_free(picture_buf);
	}
	avio_close(pFormatCtx->pb);
	avformat_free_context(pFormatCtx);

	fclose(fp_in);

	system("pause");
	return 0;
}

结果

运行程序,将输入 YUV 文件编码为 HEVC(H.265) 文件,以下是其信息:

ffmpeg hevc,FFmpeg,ffmpeg,音视频,h.265,视频编解码

ffmpeg hevc,FFmpeg,ffmpeg,音视频,h.265,视频编解码

用 VLC media player 播放:

ffmpeg hevc,FFmpeg,ffmpeg,音视频,h.265,视频编解码

可以正常播放。

工程文件下载

GitHub:UestcXiye / Simplest-FFmpeg-Video-Encoder-H.265

CSDN:Simplest FFmpeg Video Encoder H.265.zip文章来源地址https://www.toymoban.com/news/detail-859707.html

到了这里,关于最简单的基于 FFmpeg 的视频编码器(YUV 编码为 HEVC(H.265))的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 编码器 | 基于 Transformers 的编码器-解码器模型

    基于 transformer 的编码器-解码器模型是 表征学习 和 模型架构 这两个领域多年研究成果的结晶。本文简要介绍了神经编码器-解码器模型的历史,更多背景知识,建议读者阅读由 Sebastion Ruder 撰写的这篇精彩 博文。此外,建议读者对 自注意力 (self-attention) 架构 有一个基本了解

    2024年02月08日
    浏览(50)
  • 火山引擎 BVE 视频图片硬件编码器演进之路

    动手点关注 干货不迷路 近日,第 17 届世界编码器大赛 MSU 2022 公布硬件编码器比赛结果,在 60 fps(帧率)的超快视频编码赛道上,火山引擎多媒体实验室自主研发的 BVE 1.1 编码器表现突出,荣获最佳 FPGA 编码器(各项指标大幅领先);并在所有硬件编码器中,技术指标获得

    2024年02月06日
    浏览(42)
  • 世界杯直播 | 抖音视频编码器优化

    动手点关注 干货不迷路 对于世界杯这样的大型体育赛事而言,视频编码算法既要在高速运动、复杂纹理的场景下确保直播内容的清晰度和流畅度,保障用户的观赛体验,又要兼顾码率、延迟等对网络传输层面尤为敏感的指标。 另外,抖音实现了业界首次的世界杯比赛支持

    2023年04月09日
    浏览(35)
  • 解码器 | 基于 Transformers 的编码器-解码器模型

    基于 transformer 的编码器-解码器模型是 表征学习 和 模型架构 这两个领域多年研究成果的结晶。本文简要介绍了神经编码器-解码器模型的历史,更多背景知识,建议读者阅读由 Sebastion Ruder 撰写的这篇精彩 博文。此外,建议读者对 自注意力 (self-attention) 架构 有一个基本了解

    2024年02月08日
    浏览(40)
  • FFmpeg报错:Specified pixel format yuvj420p is invalid or not supported(用ffmpeg程序查看编码器支持像素格式命令)

    这是因为我们把海康rtsp视频流packet解封装后,它frame的像素格式是 yuvj420p(AV_PIX_FMT_YUVJ420P) 的,然后我们又指定编码器上下文的像素格式 pix_fmt = AV_PIX_FMT_YUVJ420P ,指定编码器为 AV_CODEC_ID_MPEG4 ,但是 AV_CODEC_ID_MPEG4 不支持 AV_PIX_FMT_YUVJ420P 像素格式,所以报了上述错误 用 ffmpe

    2023年04月13日
    浏览(75)
  • H265、VP9、AV1视频编码器性能对比

    目前在视频编解码器中,H264 已经成为绝对的主流,被大部分设备、浏览器所支持。虽然有更先进的编码器推出,但是受限于推广速度和设备支持成本,一直未能成为主流。 今年公司的目标是持续降本增效,现在将”屠刀“指向了视频业务的存储成本。视频文件存储主要两块

    2024年02月03日
    浏览(37)
  • 基于堆叠⾃编码器的时间序列预测 深层神经网络

    自适应迭代扩展卡尔曼滤波算法(AIEK)是一种滤波算法,其目的是通过迭代过程来逐渐适应不同的状态和环境,从而优化滤波效果。 该算法的基本思路是在每一步迭代过程中,根据所观测的数据和状态方程,对滤波器的参数进行自适应调整,以便更好地拟合实际数据的分布

    2024年02月09日
    浏览(25)
  • SSR-Encoder:用于主题驱动生成的通用编码器详解_AIGC-图片生成视频系列

    本文介绍了SSR-Encoder,一种用于主题驱动生成的通用编码器,能够根据文本提示或掩码查询生成图像,无需额外的测试时间微调。文章详细解释了SSR-Encoder的贡献概述、方法详解以及综合结果,展示了其在图像生成和视频生成方面的有效性。

    2024年02月02日
    浏览(102)
  • 7、江科大stm32视频学习笔记——中断的应用:对射式红外传感器计次&旋转编码器计次

    目录 1、标志位函数 2、 初始化的中断的步骤 3、对射式红外传感器计次 (1)接线图 (2)CountSensor.c (3)main.c 4、旋转编码器计次 (1)接线图(旋转编码器接在PB1、PB0引脚) (2)Encoder.c (3)main.c 5、建议 //在 主程序 中查看标志位和清楚标志位,用以下两个函数,能不能

    2024年02月11日
    浏览(30)
  • 【信号处理】基于CNN自编码器的心电信号异常检测识别(tensorflow)

    本项目主要实现卷积自编码器对于异常心电ECG信号的检测和识别,属于无监督学习中的生理信号检测的典型方法之一。   读取心电信号 信号可视化    信号均值计算及可视化  训练/测试数据划分 搭建自编码器 模型训练 训练可视化   信号重建可视化 计算重建MAE误差  异常

    2024年04月23日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包