FFmpeg--解封装流程
文章目录
- 解复用流程:
- 函数分析:
- 代码实现:
- 运行结果:
解复用流程:
- avformat_alloc_context 分配解复用器上下文
- avformat_open_input 根据url打开本地文件或网络流
- avformat_find_stream_info 读取媒体的部分数据包以获取码流信息
- av_read_frame 从文件中读取数据包
- avformat_close_input 关闭解复用器
函数分析:
1 avformat_open_input能否不调用avformat_alloc_context?
int avformat_open_input(AVFormatContext **ps, …);
函数说明:
May be a pointer to NULL, in which case an AVFormatContext is allocated by this
function and written into ps.
第一个参数可以传入空指针,内部为其分配空间
故可以在栈上定义的,AVFormatContext *ifmt_ctx = NULL;
2 AVFormatContext * ifmt_ctx 指针做参数传入解封装函数
AVFormatContext 是封装格式上下文结构体,保存了视频文件封装格式相关信息,可以通过ifmt_ctx指针可以用来读取文件相关信息,如文件路径,码流,文件时长,媒体流数量。
3 AVStream * in_stream 指针接收 ifmt_ctx指针指向的流文件
AVStream 对应文件中的一个流结构体,可以用来获取音频相关参数,如采样率
4 av_read_frame 音频包队列读取过程
首先对 AVPacket *pkt 申请空间,然后while(1)循环,循环体内部先通过av_read_frame读取音频包,获取音频信息,
之后将pkt 置空,读取完成后,释放pkt 空间
5 av_packet_unref 和 av_packet_free 的使用
void av_packet_unref(AVPacket *pkt);
void av_packet_free(AVPacket **pkt);
av_packet_unref(pkt) 将结构体置空,最后通过av_packet_free释放掉内存(先置空后释放内存,不然会导致内存泄露)
6 关闭解复用器
void avformat_close_input(AVFormatContext **s);
代码实现:
#include <stdio.h>
#include <libavformat/avformat.h>int main(int argc, char **argv)
{const char *filename = "123.mp4";AVFormatContext *ifmt_ctx = NULL;int audioindex = -1; // 音频索引// 打开文件int ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL);avformat_find_stream_info(ifmt_ctx, NULL);// 文件名printf_s("open success file :%s\n", filename);//媒体流数量printf("stream number:%d\n", ifmt_ctx->nb_streams);for (uint32_t i = 0; i < ifmt_ctx->nb_streams; i++){AVStream *in_stream = ifmt_ctx->streams[i];// 音频流、视频流、字幕流//如果是音频流,则打印音频的信息if (AVMEDIA_TYPE_AUDIO == in_stream->codecpar->codec_type){// sample_rate: 音频编解码器的采样率,单位为Hzprintf("samplerate:%dHz\n", in_stream->codecpar->sample_rate);}audioindex = i; // 获取音频的索引}AVPacket *pkt = av_packet_alloc();int pkt_count = 0;printf("\nav_read_frame start:\n");while (1){ret = av_read_frame(ifmt_ctx, pkt);if (ret < 0){printf("av_read_frame end\n");break;}if(pkt_count++ < 2){if (pkt->stream_index == audioindex){printf("audio pts: %lld\n", pkt->pts);printf("audio pos: %lld\n", pkt->pos);}}av_packet_unref(pkt);}if(pkt)av_packet_free(&pkt);if(ifmt_ctx)avformat_close_input(&ifmt_ctx);getchar();return 0;
}
运行结果:
open success file :123.mp4
stream number:2
samplerate:48000Hzav_read_frame start:
audio pts: -678
audio pos: 48
av_read_frame end