[ffmpeg系列 03] 文件、流地址(视频)解码为YUV

news2024/9/24 3:22:17

一  代码

ffmpeg版本5.1.2,dll是:ffmpeg-5.1.2-full_build-shared。x64的。

文件、流地址对使用者来说是一样。
流地址(RTMP、HTTP-FLV、RTSP等):信令完成后,才进行音视频传输。信令包括音视频格式、参数等协商。

接流的在实际中的应用:1 展示,播放。2 给算法用,一般是需要RGB格式的。

#ifndef _DECODE_H264_H_
#define _DECODE_H264_H_
#include <string>

extern  "C"
{
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
#include "libavutil/avutil.h"
#include "libavutil/mathematics.h"
#include "libavutil/time.h"
#include "libavutil/pixdesc.h"
#include "libavutil/display.h"
};

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


class CDecodeH264
{
public:
	CDecodeH264();
	~CDecodeH264();

public:


public:
	int DecodeH264();
	int  Start();
	int  Close();

	int  DecodeH264File_Init();
	int  ReleaseDecode();
	void H264Decode_Thread_Fun();
	std::string  dup_wchar_to_utf8(const wchar_t* wstr);
	double get_rotation(AVStream *st);

public:
	AVFormatContext*       m_pInputFormatCtx = nullptr;
	AVCodecContext*        m_pVideoDecodeCodecCtx = nullptr;
	const AVCodec*           m_pCodec = nullptr;	
	SwsContext*                m_pSwsContext = nullptr;
	AVFrame*                    m_pFrameScale = nullptr;
	AVFrame*                    m_pFrameYUV = nullptr;
	AVPacket*                   m_pAVPacket = nullptr;
	
	enum AVMediaType		m_CodecType;
	int                                    m_output_pix_fmt;
	int                                    m_nVideoStream = -1;
	int                                    m_nFrameHeight = 0;
	int                                    m_nFrameWidth = 0;
	int                                    m_nFPS;
	int                                    m_nVideoSeconds;

	FILE*         m_pfOutYUV = nullptr;
	FILE*         m_pfOutYUV2 = nullptr;
};
#endif



#include "DecodeH264.h"
#include <thread>
#include <functional>
#include <codecvt>
#include <locale>


char av_error2[AV_ERROR_MAX_STRING_SIZE] = { 0 };
#define av_err2str2(errnum) av_make_error_string(av_error2, AV_ERROR_MAX_STRING_SIZE, errnum)


CDecodeH264::CDecodeH264()
{	
}


CDecodeH264::~CDecodeH264()
{
	ReleaseDecode();
}

std::string  CDecodeH264::dup_wchar_to_utf8(const wchar_t* wstr)
{
	std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
	return converter.to_bytes(wstr);
}

//Side data : 
//displaymatrix: rotation of - 90.00 degrees
double CDecodeH264::get_rotation(AVStream *st)
{
	uint8_t* displaymatrix = av_stream_get_side_data(st,
		AV_PKT_DATA_DISPLAYMATRIX, NULL);
	double theta = 0;
	if (displaymatrix)
		theta = -av_display_rotation_get((int32_t*)displaymatrix);

	theta -= 360 * floor(theta / 360 + 0.9 / 360);

	if (fabs(theta - 90 * round(theta / 90)) > 2)
		av_log(NULL, AV_LOG_WARNING, "Odd rotation angle.\n"
			"If you want to help, upload a sample "
			"of this file to https://streams.videolan.org/upload/ "
			"and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)");

	return theta;
}

int CDecodeH264::DecodeH264File_Init()
{
    avformat_network_init(); //流地址需要

	m_pInputFormatCtx = avformat_alloc_context();

	
	std::string strFilename = dup_wchar_to_utf8(L"测试.h264");
	//std::string strFilename = dup_wchar_to_utf8(L"rtmp://127.0.0.1/live/now");	
	int ret = avformat_open_input(&m_pInputFormatCtx, strFilename.c_str(), nullptr, nullptr);
	if (ret != 0) {
		char* err_str = av_err2str2(ret);
		printf("fail to open filename: %s, return value: %d,  %s\n", strFilename.c_str(), ret, err_str);
		return -1;
	}

	ret = avformat_find_stream_info(m_pInputFormatCtx, nullptr);
	if (ret < 0) {
		char* err_str = av_err2str2(ret);
		printf("fail to get stream information: %d, %s\n", ret, err_str);		
		return -1;
	}


	for (int i = 0; i < m_pInputFormatCtx->nb_streams; ++i) {
		const AVStream* stream = m_pInputFormatCtx->streams[i];
		if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
			m_nVideoStream = i;
			printf("type of the encoded data: %d, dimensions of the video frame in pixels: width: %d, height: %d, pixel format: %d\n",
				stream->codecpar->codec_id, stream->codecpar->width, stream->codecpar->height, stream->codecpar->format);
		}
	}
	if (m_nVideoStream == -1) {
		printf("no video stream\n");
		return -1;
	}
	printf("m_nVideoStream=%d\n", m_nVideoStream);

	

	
    //获取旋转角度
	double theta = get_rotation(m_pInputFormatCtx->streams[m_nVideoStream]);
	

	m_pVideoDecodeCodecCtx = avcodec_alloc_context3(nullptr);
	avcodec_parameters_to_context(m_pVideoDecodeCodecCtx,\
             m_pInputFormatCtx->streams[m_nVideoStream]->codecpar);
	m_pCodec = avcodec_find_decoder(m_pVideoDecodeCodecCtx->codec_id);
	if (m_pCodec == nullptr)
	{
		return -1;
	}

	m_nFrameHeight = m_pVideoDecodeCodecCtx->height;
	m_nFrameWidth = m_pVideoDecodeCodecCtx->width;
	printf("w=%d h=%d\n", m_pVideoDecodeCodecCtx->width, m_pVideoDecodeCodecCtx->height);
	

	if (avcodec_open2(m_pVideoDecodeCodecCtx, m_pCodec, nullptr) < 0)
	{
		return -1;
	}

	//读文件知道视频宽高
	m_output_pix_fmt = AV_PIX_FMT_YUV420P; //AV_PIX_FMT_NV12;
	m_pSwsContext = sws_getContext(m_pVideoDecodeCodecCtx->width, m_pVideoDecodeCodecCtx->height,
		m_pVideoDecodeCodecCtx->pix_fmt, m_pVideoDecodeCodecCtx->width, m_pVideoDecodeCodecCtx->height,
		(AVPixelFormat)m_output_pix_fmt, SWS_FAST_BILINEAR, nullptr, nullptr, nullptr);



	//解码后的视频数据
	m_pFrameScale = av_frame_alloc();
	m_pFrameScale->format = m_output_pix_fmt;

	m_pFrameYUV = av_frame_alloc();
	m_pFrameYUV->format = m_output_pix_fmt; //mAVFrame.format is not set
	m_pFrameYUV->width = m_pVideoDecodeCodecCtx->width;
	m_pFrameYUV->height = m_pVideoDecodeCodecCtx->height;
	printf("m_pFrameYUV pix_fmt=%d\n", m_pVideoDecodeCodecCtx->pix_fmt);

	av_frame_get_buffer(m_pFrameYUV, 64);
	

	char cYUVName[256];
	sprintf(cYUVName, "%d_%d_%s.yuv", m_nFrameWidth, m_nFrameHeight, av_get_pix_fmt_name(m_pVideoDecodeCodecCtx->pix_fmt));
	fopen_s(&m_pfOutYUV, cYUVName, "wb");

	char cYUVName2[256];
	sprintf(cYUVName2, "%d_%d_%s_2.yuv", m_nFrameWidth, m_nFrameHeight, av_get_pix_fmt_name(m_pVideoDecodeCodecCtx->pix_fmt));
	fopen_s(&m_pfOutYUV2, cYUVName2, "wb");

	printf("leave init\n");

	return   0;
}


void CDecodeH264::H264Decode_Thread_Fun()
{
	int   nFrameFinished = 0;
	int i = 0;
	int  ret;
	m_pAVPacket = av_packet_alloc();

	while (true) {
		ret = av_read_frame(m_pInputFormatCtx, m_pAVPacket);
	
			if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
				av_packet_unref(m_pAVPacket);
				printf("read_frame break");
				break;
			}

		if (m_pAVPacket->stream_index == m_nVideoStream)
		{

			int  send_packet_ret = avcodec_send_packet(m_pVideoDecodeCodecCtx, m_pAVPacket);
			printf("encode video send_packet_ret %d\n", send_packet_ret);
			int receive_frame_ret = avcodec_receive_frame(m_pVideoDecodeCodecCtx, m_pFrameScale);
			char* err_str = av_err2str2(receive_frame_ret);
			printf("frame w=%d, h=%d, linesize[0]=%d, linesize[1]=%d\n", m_pFrameScale->width, m_pFrameScale->height, m_pFrameScale->linesize[0], m_pFrameScale->linesize[1]);
			
			

			if (receive_frame_ret == 0)
			{
				++i;

				int iReturn = sws_scale(m_pSwsContext, m_pFrameScale->data,
					m_pFrameScale->linesize, 0, m_nFrameHeight,
					m_pFrameYUV->data, m_pFrameYUV->linesize);
				printf("frame w=%d, h=%d, linesize[0]=%d, linesize[1]=%d\n", m_pFrameYUV->width, m_pFrameYUV->height, m_pFrameYUV->linesize[0], m_pFrameYUV->linesize[1]);
				/*if (0 != iReturn)
				{
					fwrite(m_pFrameYUV->data[0], 1, m_nFrameWidth * m_nFrameHeight, m_pfOutYUV);
					fwrite(m_pFrameYUV->data[1], 1, m_nFrameWidth * m_nFrameHeight /4, m_pfOutYUV);
					fwrite(m_pFrameYUV->data[2], 1, m_nFrameWidth * m_nFrameHeight /4, m_pfOutYUV);
				}*/
				//用linesize更能兼容特殊的宽
				if (0 != iReturn)
				{					
					for (int i = 0; i < m_nFrameHeight; ++i) {
						fwrite(m_pFrameYUV->data[0] + i * m_pFrameYUV->linesize[0], 1, m_nFrameWidth, m_pfOutYUV2);
					}
					for (int i = 0; i < m_nFrameHeight / 2; ++i) {
						fwrite(m_pFrameYUV->data[1] + i * m_pFrameYUV->linesize[1], 1, m_nFrameWidth / 2, m_pfOutYUV2);
					}
					for (int i = 0; i < m_nFrameHeight / 2; ++i) {
						fwrite(m_pFrameYUV->data[2] + i * m_pFrameYUV->linesize[2], 1, m_nFrameWidth / 2, m_pfOutYUV2);
					}
				}				

			}
		}
		av_packet_unref(m_pAVPacket);
	}
}


int CDecodeH264::DecodeH264()
{
	if (DecodeH264File_Init() != 0)
	{
		return   -1;
	}

	auto video_func = std::bind(&CDecodeH264::H264Decode_Thread_Fun, this);
	std::thread  video_thread(video_func);
	video_thread.join(); 

	return 0;
}


int CDecodeH264::Start()
{
	DecodeH264();
	
	return  1;
}



int CDecodeH264::Close()
{
	return   0;
}


int  CDecodeH264::ReleaseDecode()
{
	if (m_pSwsContext)
	{
		sws_freeContext(m_pSwsContext);
		m_pSwsContext = nullptr;
	}
	if (m_pFrameScale)
	{
		av_frame_free(&m_pFrameScale);//av_frame_alloc()对应
	}

	if (m_pFrameYUV)
	{
		av_frame_free(&m_pFrameYUV);
	}

	avcodec_close(m_pVideoDecodeCodecCtx);

	avformat_close_input(&m_pInputFormatCtx);


	return 0;

}
#include <iostream>
#include <Windows.h>

#include "1__DecodeH264/DecodeH264.h"


int main()
{

    CDecodeH264* m_pDecodeVideo = new CDecodeH264();
	m_pDecodeVideo->Start();


    return 0;
}

图是雷神博客的:注册函数废弃了,解码函数变了。

二  相关的结构体,方便记忆


1 AVFrame是未压缩的,解码后的数据。
  AVPacket是压缩的,解码前的数据。
  知道了这个,编码的send_frame、receive_packet,解码的send_packet、receive_frame,容易记住了。

2 2个Context(上下文):Format(混合文件、流地址)、Codec(单个编码格式,比如H264、AAC,编解码实现)
  AVFormatContext*  m_pInputFormatCtx;
  AVCodecContext*   m_pVideoDecodeCodecCtx;
  m_pInputFormatCtx会用到的函数:avformat_open_input、avformat_find_stream_info、 
  av_read_frame、avformat_close_input。
  m_pOutputFormatCtx会用到的函数:avcodec_find_decoder、avcodec_open2、
   avcodec_send_packet、 avcodec_receive_frame。


3 AVCodec结构体
const  AVCodec  ff_h264_decoder = {
    .name                  = "h264",
    .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
    .type                  = AVMEDIA_TYPE_VIDEO,
    .id                    = AV_CODEC_ID_H264,
    .priv_data_size        = sizeof(H264Context),
    .init                  = h264_decode_init,
    .close                 = h264_decode_end,
    .decode                = h264_decode_frame,
    ……
}

static const AVCodec * const codec_list[] = {
...
  &ff_h264_decoder,
...
};

三 兼容性问题

1 文件名带中文,需要转换。

2 播放竖屏视频(手机录的那种),获取旋转角度。

截图是ffmpeg做法:获取角度后,使用filter调整。

3 宽比较特殊,不是16,32的整数。(比如544x960,544是32的倍数)。用linesize[i]代替宽。

linesize跟cpu有关,是cpu 16、32的倍数。

其它,待更新。

四  为什么需要sws_scale?转换到统一格式I420

sws_scale作用:1 分辨率缩放、 2 不同YUV、RGB格式转换。

H264有记录编码前的YUV采样格式,chroma_format_idc,在sps里。如果没有这个字段,说明该字段用的默认值1,即yuv 4:2:0。

如果YUV的采样格式是yuv 4:2:0,也不要求缩放,不需要sws_scale。

avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame);

frame->format记录了yuv的类型。

ffmpeg默认解码成:编码前的yuv格式。即m_pVideoDecodeCodecCtx->pix_fmt。

int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
{
  ...
  frame->format              = avctx->pix_fmt;
  ...
}

五  不同格式的time_base

H264的time_base:1/1200000。

flv:音视频都是1/1000。

mp4:视频1/12800(帧率25,怎么算出来的?),音频:1/48000(1/采样频率)。

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

day10 用栈实现队列 用队列实现栈

题目1&#xff1a;232 用栈实现队列 题目链接&#xff1a;232 用栈实现队列 题意 用两个栈实现先入先出队列&#xff08;一个入栈&#xff0c;一个出栈&#xff09;&#xff0c;实现如下功能&#xff1a; 1&#xff09;push&#xff1a;将元素x推到队列末尾 2&#xff09;…

MyBatisPlus-基本配置与常见应用

MyBatisPlus 一、快速入门 MyBatis Plus是基于MyBatis的增强工具&#xff0c;提供了更简单、更便捷的方式来操作数据库。它是一个功能丰富的ORM&#xff08;对象关系映射&#xff09;框架&#xff0c;可以帮助开发人员更快速地进行数据库操作。 MyBatis Plus的主要特点如下&…

【知识点】:ECMAScript简介及特性

一.简介 什么是ECMAScript&#xff1f; ECMAScript是由网景的布兰登艾奇开发的一种脚本语言的标准化规范&#xff1b;最初命名为Mocha&#xff0c;后来改名为LiveScript&#xff0c;最后重命名为JavaScript。1995年12月&#xff0c;升阳与网景联合发表了JavaScript。1996年11月…

华为HarmonyOS 创建第一个鸿蒙应用 运行Hello World

使用DevEco Studio创建第一个项目 Hello World 1.创建项目 创建第一个项目&#xff0c;命名为HelloWorld&#xff0c;点击Finish 选择Empty Ability模板&#xff0c;点击Next Hello World 项目已经成功创建&#xff0c;接来下看看效果 2.预览 Hello World 点击右侧的预…

K8s-应用数据

应用数据 1 应用数据解析 k8s应用数据类型和步骤解析 k8s如何使用数据功能 k8s使用各种数据类型的配置 2 应用数据实践 emptyDir实践 资源对象文件内容 apiVersion: v1 kind: Pod metadata:name: sswang-emptydir spec:containers:- name: nginx-webimage: kubernetes-reg…

操作系统内存碎片

大家好&#xff0c;我叫徐锦桐&#xff0c;个人博客地址为www.xujintong.com&#xff0c;github地址为https://github.com/jintongxu。平时记录一下学习计算机过程中获取的知识&#xff0c;还有日常折腾的经验&#xff0c;欢迎大家访问。 一、前言 内存碎片是指无法被利用的内…

C# 关于反射的简单示例

写在前面 在日常开发中&#xff0c;我们经常使用反射来动态获取关于类的信息&#xff0c;或者是动态给类实例成员赋值&#xff1b;反射提供了封装程序集、模块和类型的对象&#xff08;Type 类型&#xff09;。可以使用反射动态创建类型的实例&#xff0c;将类型绑定到现有对象…

关闭stp环路的实验演示

在日常的网络规划设计中&#xff0c;为了提高网络的可靠性&#xff0c;通常会采取链路冗余&#xff0c;但是会导致网络中形成环路。有的小伙伴就会发问了&#xff0c;明明增加了链路&#xff0c;网络的可靠性不仅没有提高&#xff0c;怎么反而导致了通信异常呢&#xff1f; 拓…

如何使用csdn中的c知道进行学习?

1.c知道 猜测是通过chatgpt训练链接到CSDN内部的文章内容等&#xff0c;进行生成的一款应用。 2.如何使用呢 打比方说&#xff0c;我想学习下多目标跟踪中的ukf&#xff0c;那么就可以输入这个关键字。 那既然是学习&#xff0c;就要进一步深究&#xff0c;有三种方式&#…

nacos server控制台打开页面空白

总结一下最近遇到的一个纠结很久的坑&#xff1b;通过docker的方式部署nacos server在服务器&#xff0c;部署启动一切正常&#xff0c;然后通过safari浏览器打开控制台的时候页面空白&#xff0c;只有一个标题&#xff1b;打开控制台报错&#xff1a;Failed to load resource:…

纳什议价解

纳什议价解 局中人在网络中所处的位置决定了他们的议价权&#xff0c;并最终导致不同的局中人在博弈中所获得的收益大小不同。下图给出了A、B、 C、D 四人参加网络交换博弈的一个稳定结局&#xff0c;其中粗线相连的节点之间达成交换&#xff0c;交换所得效益标记在了节点上方…

docker 安装elasticsearch、kibana、cerebro、logstash

安装步骤 第一步安装 docker 第二步 拉取elasticsearch、kibana、cerebro、logstash 镜像 docker pull docker.elastic.co/elasticsearch/elasticsearch:7.10.2 docker pull docker.elastic.co/kibana/kibana:7.10.2 docker pull lmenezes/cerebro:latest docker pull l…

【SpringCloud Alibaba笔记】(2)Sentinel实现熔断与限流

Sentinel 概述 官网&#xff1a;https://github.com/alibaba/Sentinel 中文文档&#xff1a;https://sentinelguard.io/zh-cn/docs/introduction.html 类似Hystrix&#xff0c;以流量为切入点&#xff0c;从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热…

JVM中虚拟机栈和本地方法栈等

jvm Java虚拟机栈本地方法栈 Java虚拟机栈 Java虚拟机栈&#xff08;VM Stack&#xff09; ​ 虚拟机栈是线程执行Java程序时&#xff0c;处理Java方法中内容的内存区域。虚拟机栈也是线程私有的区域&#xff0c;每个Java方法被调用的时候&#xff0c;都会在虚拟机栈中创建出…

实战-docker方式给自己网站部署prometheus监控ecs资源使用情况-2024.1.7(测试成功)

title: 实战-docker方式给自己网站部署prometheus监控ecs资源使用情况-2024.1.7(测试成功) date: 2024-1-7 categories: linux tags: promtheues summary: prometheusgrafana 更新于&#xff1a;2024年1月7日 实战-docker方式给自己网站部署prometheus监控ecs资源使用情况-2024…

二叉树与堆的深度解析:数据结构中的关键概念及应用

. 个人主页&#xff1a;晓风飞 专栏&#xff1a;数据结构|Linux|C语言 路漫漫其修远兮&#xff0c;吾将上下而求索 文章目录 前言树概念注意&#xff1a; 树的基本概念及术语基本概念及术语以家谱为例 树的表示孩子兄弟表示法简介优势应用示例 树在实际中的运用文件系统的目录树…

【Maven笔记3】Maven基础入门案例

本篇通过一个最基础的入门案例&#xff0c;熟悉一下maven最基础的使用方法。 编写POM maven项目的核心是pom.xml文件&#xff0c;pom定义了项目的基本信息&#xff0c;用于描述项目如何构建&#xff0c;声明项目依赖等等。 这里我们新建一个maven-demo-hello项目&#xff0c;…

VS Code结合Live Server插件快速搭建小游戏并发布至公网可随时远程访问

文章目录 前言1. 编写MENJA小游戏2. 安装cpolar内网穿透3. 配置MENJA小游戏公网访问地址4. 实现公网访问MENJA小游戏5. 固定MENJA小游戏公网地址 前言 本篇教程&#xff0c;我们将通过VS Code实现远程开发MENJA小游戏&#xff0c;并通过cpolar内网穿透发布到公网&#xff0c;分…

黑莓系统的安全性如何?

黑莓系统的安全性非常高&#xff01; 在过去很长一段时间里&#xff0c;都被认为是手机市场上最安全的操作系统。这主要得益于黑莓在安全性方面的重视和投入。 &#xff08;在世界上最安全的 6 款手机排名中&#xff0c;iPhone未能入围&#xff09; 世界上最安全的 6 款手机&…

CNN——ResNet

深度残差网络&#xff08;Deep residual network, ResNet&#xff09;的提出是CNN图像史上的一件里程碑事件&#xff0c;并且让深度学习真正可以继续做下去&#xff0c;斩获2016 CVPR Best Paper。此外ResNet的作者都是中国人&#xff0c;一作何恺明。ResNet被提出以后很多的网…