5.1 avcodec_find_decoder、AVCodecContext、avcodec_parameters_to_context
1、确定解码器,通过avcodec_find_decoder获取解码器,返回AVCodec这个结构体
avcodec_register_all(); // 注册 所有解码器
AVCodec *avcodec_find_decoder(enum AVCodecID id) // 通过传递id号来获取对应的解码器
AVCodec *avcodec_find_decoder_by_name(const char * name) // 通过字符串获取解码器————硬解码
avcodec_find_decoder_by_name("h264_mediacodec"); // 通过名字
2、解码时候还需要解码上下文 AVCodecContext(本次解码的信息)
AVCodecContext *avcodec_alloc_context3(const AVCodec *codec) // 申请创建上下文空间
void avcodec_free_context(AVCodecContext **avctx) // 空间释放
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec,AVDictionary **options); // 打开解码器
/libavcodec/options_table.h 参数设置
int thread_count; // 多线程解码,充分利用CPU资源
time_base; // 时间基数
3、参数设置,除了手动设置,还可以通过函数avcodec_parameters_to_context
avcodec_parameters_to_context,将参数设置直接进行拷贝,从AVStream里面进行拷贝
5.3 AVFrame (在打开解码器上下文之后开始逐帧进行解码,解码前需要先关注AVFrame这个结构体,用于存放解码后的数据)
AVFrame就是一幅独立的图像!!!
AVFrame * frame = av_frame_alloc() // 分配空间(分配和释放与AVPacket相同)
void av_frame_free(AVFrame **frame) // 空间释放
int av_frame_ref(AVFrame *dst, const AVFrame *src); // 引用计数
AVFrame *av_frame_clone(const AVFrame *src); // 复制,重新创建空间,引用空间+1
void av_frame_unref(AVFrame *frame); // 直接引用计数减一(空间释放方法二)
uint8_t *data[AV_NUM_DATA_POINTERS];
int linesize[AV_NUM_DATA_POINTERS];
int width,height; int nb_samples; // nb_samples单通道的样本数量,一个样本2字节
int64_t pts; int64_t pkt_dts;
int sample_rate; uint64_t channel_layout; int channels;
int format; // AVPixelFormat AVSapleFormat; // 像素格式
linesize:存放大小,目的是为了对齐
宽度一行数据的大小
通道一行数据的大小
5.4 解码函数
avcodec_send_packet,将packet写到解码队列中去
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt); // 内存开销问题
avcodec_receive_frame,从已解码成功的数据中取出一个frame
int avcodec_receive_frame(AVCodecContext *avctx,AVFrame *frame);
ps:send一次,receive不一定是一次
问题集锦:1、播放最后几帧显示不了,那是缓冲帧的问题。传null,(解决播放时候最后几帧不显示的问题)
// 发送packet 到解码线程,send传NULL(将pkt换成null)后调用多次receive,会取出所有的缓冲帧
re = avcodec_send_packet(cc,pkt);
2、要加头文件
包含了库之后要把对应的头文件也包含进来
3 重采样有报错
5.6 视频像素格式转换和尺寸转换(可以用GPU来做,效率更高)ffmpeg接口简单(唯一优势),但性能开销大
sws_getContext 像素格式转换上下文,每次都会新创建
struct SwsContext *sws_getCachedContext(struct SwsContext *context(传格式转换上下文地址),
int srcW(原宽), int srcH(原高), enum AVPixelForamt srcFormat(原像素格式),
int dstW(目标宽), int dstH(目标高), enum AVPixelFormat dstFormat(目标像素格式),
int flags, SwsFilter * srcFilter,
SwsFilter *dstFilter, const double *param );
第一个函数sws_getCachedContext只是创建好像素格式转换的上下文,具体的逐帧转换用sws_scale
int sws_scale(struct Swscontext * c, const uint8_t *const srcSlice[],
const int srcStride[](linesize,一行大小,宽度), int srcSliceY(0), int srcSliceH(图像高度);
uint8_t *const dst[](目标地址), const int dstStride[](输出的一行大小,linesize));
void sws_freeContext(struct SwsContext *swsContext); // 释放上下文,传地址就可以
int flags, SwsFilter * srcFilter, 这里的flag指的是各种算法,主要是针对尺寸的变化,不涉及像素格式转化,具体如下
5.9 音频重采样
SwrContext
音频解码出来不能直接播放,需要重采样(解码出来是32位,声卡不支持,所以需要重采样)
ffmpeg所有处理都需要上下文,因为是C 语言的一个特点,上下文,不像C++ 有个对象就行了,而C语言需要有个指针贯穿前后,将他们关联起来,所以有这么一个结构体的上下文
SwrContext *swr_alloc(void); // 分配和初始化
SwrContext *swr_alloc_set_opts(
struct SwrContext *s, //重采样上下文
int64_t out_ch_layout, // 输出的声道标准
AVSampleFormat out_sample_fmt, // 输出的样本格式
int out_sample_rate, // 输出的样本率
int64_t in_ch_layout,
AVSampleFormat in_sample_fmt, // 输入的格式
int in_sample_rate, // 输入的样本率
int log_offset,void *log_ctx); // 两个日志传0就行
int swr_init(struct SwrContext *s); // 初始化上下文,然后进行格式转换
void swr_free(struct SwrContext **s); // 空间有申请就有释放,清零
swr_convert 转换函数,将一帧帧的音频做重采样
int swr_convert(struct SwrContext *s, // 重采样的上下文
uint8_t ** out, // 输出的指针(双指针,传指针地址或者数组)
int out_count, // 输出的单通道的样本数 nb_samples
const uint8_t **in, // 输入的指针
int in_count); // 单通道的样本数
#include <iostream>
#include<thread> //线程
extern "C" {
#include "libavformat/avformat.h"
#include"libavcodec/avcodec.h"
#include "libswscale/swscale.h" // 尺寸变化头文件,用于格式转换
#include "libswresample/swresample.h" // 重采样头文件
}
using namespace std;
#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avutil.lib") //ffmpeg库里面包含的库
#pragma comment(lib,"avcodec.lib")
#pragma comment(lib,"swscale.lib")
#pragma comment(lib,"swresample.lib")
static double r2d(AVRational r) //static仅在当前文件有效
{
return r.den == 0 ? 0 : (double)r.num / (double)r.den;
}
void XSleep(int ms) //用毫秒展示
{
// C++ 11
chrono::milliseconds du(ms);
this_thread::sleep_for(du);
}
int main(int argc, char *argv[])
{
const char * path = "WeChat_20220914115137.mp4";
cout << "Test Demux FFmpeg.club" << endl;
// 初始化封装库
//av_register_all(); // 这个函数已经废弃
// 初始化网络库(可以打开rtsp(网络摄像头) rtmp(直播) http(网站或者直播) 协议的流媒体视频)
avformat_network_init();
// 注册解码器
// avcodec_register_all(); // 已经弃用
// 参数设置
AVDictionary *opts = NULL;
// 添加属性
//设置rtsp流以tcp协议打开
av_dict_set(&opts, "rtsp_transport", "tcp", 0);
// 网络延时时间
av_dict_set(&opts, "max_delay", "500", 0);
// 解封装上下文
AVFormatContext *ic = NULL; //ic指针指向null
// 打开视频
int re = avformat_open_input(
&ic, // 传指针没有意义,要传指针的地址 相当于 &(*ic),指针传进去函数调用后,会把AVFormatContext的空间用ic申请出来,并且在里面填入打开的视频信息内容
path, // 路径,先写死
0, // 0或者null 表示自动选择解封装器
&opts // 参数设置,传递的是指针的指针,比如rtsp的延时时间
);
if (re != 0)
{
char buf[1024] = { 0 };
av_strerror(re, buf, sizeof(buf) - 1); // 将re传进去,用buf存储,buf长度不让buf溢出
cout << "open" << path << "failed!:" << buf << endl; // 打印失败原因
getchar();
return -1;
}
cout << "open" << path << "success!" << endl; // re = 0,成功
// 获取流信息
re = avformat_find_stream_info(ic, 0);
// 音视频索引,读取时区分音视频
int videoStream = 0;
int audioStream = 1;
// 获取总时长 毫秒
int totalMs = ic->duration / (AV_TIME_BASE / 1000);
cout << "totalMs = " << totalMs << endl;
// 打印视频流详细信息
av_dump_format(ic, 0, path, 0);//第四个参数 含义:input(0) or output(1)
// 获取音视频流信息(遍历,函数获取)
for (int i = 0; i < ic->nb_streams; i++)
{
// 如何判断音视频?找到索引后,取出AVStream后找到下标,存放在ic里面
AVStream *as = ic->streams[i];
cout << "codec_id = " << as->codecpar->codec_id << endl; // 打开解封装器
cout << "format = " << as->codecpar->format << endl; // 存储格式,format = 8,平面存储方式
// 一定要重采样,转化成16位/24位,否则无法播放
// 音频
if (as->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
{
audioStream = i;
cout << i << "音频信息" << endl;
cout << "sample_rate = " << as->codecpar->sample_rate << endl; // 样本率
cout << "channels = " << as->codecpar->channels<< endl; // 通道数,单通道还是双通道
cout << "audio fps = " << r2d(as->avg_frame_rate)<<endl;
// 那么一帧数据是什么??? 一定量的样本数
// 那一帧数据存多少样本数
// 一帧数据的单通道样本数
cout << "frame_size = " << as->codecpar->frame_size << endl; //1024
// 双通道 = 1024 * 2(双通道)* 2 (16位,8位1字节) = 4096
// fps = sample_rate / frame_size;
}
// 视频
else if (as->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoStream = i;
cout << i << "视频信息" << endl; // 0是视频1是音频
cout << "width=" << as->codecpar->width << endl;
cout << "height=" << as->codecpar->height << endl;
// 帧率 fps 视频的fps一定是整数,音频 的fps有可能是分数
cout << "video fps = " << r2d(as->avg_frame_rate) << endl;
// 对于视频,一帧数据一帧画面就是一幅图像
}
}
//第二种方法获取流信息(第一种方法是遍历)
// 获取视频流
videoStream = av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); // -1是自动获取
// ic->streams[videoStream] // 通过ic->streams下标就可以访问到,从而不需要遍历
/
// 视频解码器打开
// 找到视频解码器解码器
const AVCodec *vcodec =avcodec_find_decoder(ic->streams[videoStream]->codecpar->codec_id);
if (!vcodec) // 如果找不到
{
cout << "can't find the codec id" << ic->streams[videoStream]->codecpar->codec_id;
getchar();
return -1;
}
cout << "find the AVCodec" << ic->streams[videoStream]->codecpar->codec_id << endl;
// 创建解码器上下文 vcc= video codeccontext
AVCodecContext *vc = avcodec_alloc_context3(vcodec);
// 复制解码器上下文配置
avcodec_parameters_to_context(vc, ic->streams[videoStream]->codecpar);
vc->thread_count = 8; // 设置成8线程
// 打开解码器上下文
re = avcodec_open2(vc, 0, 0);
if (re != 0) // 失败
{
char buf[1024] = { 0 };
av_strerror(re, buf, sizeof(buf) - 1); // 将re传进去,用buf存储,buf长度不让buf溢出
cout << "avcodec_open2 failed!:" << buf << endl; // 打印失败原因
getchar();
return -1;
}
cout << "videoavcodec_open2 success!" << endl;
/
// 音频解码器打开
// 找到音频解码器解码器 acodec:audio codec
const AVCodec *acodec = avcodec_find_decoder(ic->streams[audioStream]->codecpar->codec_id);
if (!acodec) // 如果找不到
{
cout << "can't find the codec id" << ic->streams[audioStream]->codecpar->codec_id;
getchar();
return -1;
}
cout << "find the AVCodec" << ic->streams[audioStream]->codecpar->codec_id << endl;
// 创建解码器上下文 vcc= video codeccontext
AVCodecContext *ac = avcodec_alloc_context3(acodec);
// 复制解码器上下文配置
avcodec_parameters_to_context(ac, ic->streams[audioStream]->codecpar);
ac->thread_count = 8; // 设置成8线程
// 打开解码器上下文
re = avcodec_open2(ac, 0, 0);
if (re != 0) // 失败
{
char buf[1024] = { 0 };
av_strerror(re, buf, sizeof(buf) - 1); // 将re传进去,用buf存储,buf长度不让buf溢出
cout << "acodec_open2 failed!:" << buf << endl; // 打印失败原因
getchar();
return -1;
}
cout << "audio avcodec_open2 success!" << endl;
// 读取一定是在关闭上下文之前
// malloc AVPacket并初始化
AVPacket *pkt = av_packet_alloc();
AVFrame *frame = av_frame_alloc(); // 申请空间
//s scale
SwsContext *vctx = NULL; // 创建像素格式和尺寸转换上下文
unsigned char *rgb = NULL; // RGB的输出数据 char带符号,会把一些图像数据弄丢失了
// 音频重采样 (转换格式、调整采样率) 上下文初始化
// AAC解码出来是float格式,32位格式,声卡不支持,转换成16位或者24位, 这里统一转成16位
// r resample 重采样
SwrContext *actx = swr_alloc(); // 重采样上下文
actx = swr_alloc_set_opts(actx,
av_get_default_channel_layout(2), // 默认2通道
AV_SAMPLE_FMT_S16, // 输出样本格式
ac->sample_rate, //输出采样率 1秒钟的音频样本数量
av_get_default_channel_layout(ac->channels), // 输入格式,通道数也是2个
ac->sample_fmt, //
ac->sample_rate, //
0, 0
);
re = swr_init(actx);
if (re != 0) // 失败
{
char buf[1024] = { 0 };
av_strerror(re, buf, sizeof(buf) - 1); // 将re传进去,用buf存储,buf长度不让buf溢出
cout << "swr_init failed!:" << buf << endl; // 打印失败原因
getchar();
return -1;
}
unsigned char *pcm = NULL;
for (;;) // 先用一个无限循环,因为不确定文件有多大
{
//av_read_frame(ic, pkt); // ic就是刚刚打开的解封装的上下文,第二个参数是pkt,要申请空间,一般是通过接口来申请
int re = av_read_frame(ic, pkt);
if (re != 0) // 读到结尾如何让其回到开头?用av_seek_frame
{
// 显示结尾后循环播放到开头第三秒的位置
cout << "===================end=======================" << endl;
int ms = 3000; // 三秒位置 根据时间基数(分数)转换
long long pos = (double)ms /(double)1000 * r2d(ic->streams[pkt->stream_index]->time_base);
// ms / 1000 转化成秒s,然后转化成浮点数,再×时间基数
av_seek_frame(ic, videoStream, pos, AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME );
// av_seek_frame 索引默认0(视频) AVSEEK_FLAG_BACKWARD往后找,且找到关键帧
continue;
//break; // 失败,直接跳出,不需要释放空间
}
cout << "pkt->size"<<pkt->size << endl; // 成功,打印大小
//显示的时间
cout << "pkt->pts" << pkt->pts << endl;
//解码时间
cout << "pkt->dts" << pkt->dts << endl;
// 转换为毫秒,方便做同步。 音频的time_base是采样率分之一,而视频有时候是千分之一,很难一致,所以将其转化成毫秒进行同步
cout << "pkt->dts = " << pkt->pts * (r2d(ic->streams[pkt->stream_index]->time_base) * 1000) << endl;
// pts×time_base分数,得出来的就是具体的多少秒 * 1000 转成ms毫秒
// 判断这帧存放音频还是视频
AVCodecContext *cc = 0;
if (pkt->stream_index == videoStream) // 视频帧率25
{
cout << "图像" << endl;
cc = vc; // 图像上下文
}
if (pkt->stream_index == audioStream) // 音频帧率44
{
cout << "音频" << endl;
cc = ac; // 音频上下文
}
//
// 解码视频
// 发送packet 到解码线程,不占用CPU send传NULL(将packet即pkt换成null)后调用多次receive,会取出所有的缓冲帧(解决播放时候最后几帧不显示的问题)
re = avcodec_send_packet(cc,pkt);
// avcodec_send_packet 返回0表示success
// 引用结束后释放
av_packet_unref(pkt); // 释放,引用计数-1, 为0释放空间
if (re != 0) // 失败
{
char buf[1024] = { 0 };
av_strerror(re, buf, sizeof(buf) - 1); // 将re传进去,用buf存储,buf长度不让buf溢出
cout << "avcodec_send_packet failed!:" << buf << endl; // 打印失败原因
continue;
}
for (;;)
{
// 接收不占用CPU,从线程中获取解码接口........注意,一次send可能对应多次的receive,需要多次接收,直到收不到为止
re = avcodec_receive_frame(cc, frame);
if (re != 0) break;
cout << "recv frame" << frame->format << "frame linesize " << frame->linesize[0] << endl;
// frame->linesize[0] = 8192 或者1920? 为了内存对齐
//aac nb_samples一般为1024
// 8192 = 1024(样本) * 4(float 32 位 4字节) * 2(双声道)
if (cc == vc) // 如果是视频的话
{
vctx = sws_getCachedContext( // cache 如果尺寸发生变化,会把上一次的清空重新创建,如果与上一次值一致,会把该值取出,不会出现空间泄露的问题
vctx, // 传上下文,如果传null会新创建
frame->width, frame->height, // 输入的宽、高
(AVPixelFormat)frame->format, //输入的格式yuv420p ,AVPixelFormat是枚举类型,格式需要强制转换一下,因为格式默认是int,
frame->width, frame->height, // 输出的宽、高
AV_PIX_FMT_RGBA, // 输出格式RGBA
SWS_BILINEAR, // 线性填充,average
0, 0, 0); // 过滤器等其他参数,无用
//if (vctx)
//{
// cout << "像素格式尺寸转换上下文创建或者获取成功success!" << endl;
//}
//else
// cout << "像素格式尺寸转换上下文创建或者获取成功failure!" << endl;
// 格式上下文创建成功后开始具体转换
if (vctx)
{
if (!rgb) // 如果rgb = null // rgb就开辟空间 = 宽 * 高 * 字节数
rgb = new unsigned char[frame->width * frame->height * 4]; // rgba 是32位,4个字节
uint8_t *data[2] = { 0 }; // uint8_t = unsigned char
data[0] = rgb;
int lines[2] = { 0 };
lines[0] = frame->width * 4; // 一行的字节数
// #####################################这一步转换的开销很大,一般是放到GPU来做
// 例如1920*1080,那就要遍历几百万次,计算开销太大
re = sws_scale( // sws_scale返回高度
vctx, // 上下文
frame->data, // 输入数据
frame->linesize, // 输入行大小(为了对齐,将1911对齐成1920)
0, // 对齐位置,从0开始
frame->height, // 输入高度
data,// 输出数据和大小
lines
);
cout << "sws_scale = " << re << endl;
}
else
cout << "像素格式尺寸转换上下文创建或者获取成功failure!" << endl;
// ##################### 到此完成图像像素格式转换 ####################
}
else // 音频
{
uint8_t *data[2] = { 0 };
if (!pcm) // 如果pcm为空
pcm = new uint8_t[frame->nb_samples * 2 * 2]; // nb_samples样本个数 *2 (样本大小(字节数),16位,16/8=2) * 2(通道数)
data[0] = pcm;
re = swr_convert(actx,
data, // 输出
frame->nb_samples, // 输出
(const uint8_t**)frame->data, // 输入
frame->nb_samples); // 输入
cout << "swr_convert = " << re << endl;
}
}
//XSleep(50); //打印频率500ms一次,一秒2次
}
av_frame_free(&frame); //指针地址释放空间
av_packet_free(&pkt); // 释放空间
if (ic) // 如果指针不为空,也就是播放成功的时候,则释放指针
{
// 释放封装上下文,并且把ic置0
avformat_close_input(&ic);
}
getchar(); // 停止
return 0;
}