[TOC]
开始前的BB
通过上一章建立好相应的开发环境后,咱们就开始撸代码了,这章简单介绍了AVFormat的解封装以及简单的应用,这章的前提知识是
- 视频文件的组成(视频轨道,音频轨道、字幕轨道等)
- H264文件格式(NALU)
走你
我们新建一个类
这个类就是写我们今天的Demo,首先是要引入头文件
#include <iostream>
extern "C" {
#include <libavformat/avformat.h>
}
复制代码
使用std的命名空间,少打几个字母,没有错 我就是这么懒
using namespace std;
复制代码
解复用
这里我们先来讲一下解复用的流程
对应到代码上
/**
* avformat 的简单使用
*
* 分离视频
*
* @param url 视频的Url(本地/网络)
*/
void chapter05_h264(const char *url) {
//打开文件流
FILE *output = fopen("./output.h264", "wb+");
//返回状态码
int ret_code;
//寻找到指定的流下标
int media_index = -1;
//分配一个存储解封装后的Packet
AVPacket *packet = av_packet_alloc();
//初始化网络
avformat_network_init();
//分配AVFormatContext
AVFormatContext *avFormatContext = avformat_alloc_context();
if (avFormatContext == nullptr) {
cout << "[error] AVFormat alloc error" << endl;
goto failed;
}
//打开输入流
ret_code = avformat_open_input(&avFormatContext, url, nullptr, nullptr);
if (ret_code < 0) {
cout << "[error] open input failed " << av_err2str(AVERROR(ret_code)) << endl;
goto failed;
}
//读取媒体文件信息
ret_code = avformat_find_stream_info(avFormatContext, nullptr);
if (ret_code < 0) {
cout << "[error] find stream info failed " << av_err2str(AVERROR(ret_code)) << endl;
goto failed;
}
//寻找到指定的视频流
media_index = av_find_best_stream(avFormatContext, AVMEDIA_TYPE_VIDE