1、yuv->H264经过编码后可以明显缩小视频文件的体积,例如我们经常看到的MP4文件其实就是由H264格式的视频文件和aac音频格式文件打包而成。
2、整个编码流程:
网上的一个关于AVFormatContext结构体的一张图,比较直观:
3、编码实现:
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavfilter/avfilter.h"
#include "libavutil/avutil.h"
#include "libavutil/ffversion.h"
#include <libavutil/imgutils.h>
#include "libswresample/swresample.h"
#include "libswscale/swscale.h"
#include "libavdevice/avdevice.h"
#include "libpostproc/postprocess.h"
}
void MainWindow::yuvToh264()
{
AVFormatContext* pFmtCtx = nullptr;
AVCodec* pCodec = nullptr;
AVStream* pVStream = nullptr;
AVCodecContext* pCodecCtx = nullptr;
AVFrame* pSrcFrame = nullptr;
uint8_t* pSrcBuffer = nullptr;
AVPacket* pkt = av_packet_alloc();
do
{
QString strOutFile = "out.h264";
//创建输出码流的上下文并初始化
if(avformat_alloc_output_context2(&pFmtCtx, nullptr, nullptr, strOutFile.toStdString().c_str()))
{
qDebug() << "cannot alloc output file context." << endl;
break;
}
//打开输出文件
if(avio_open(&pFmtCtx->pb, strOutFile.toStdString().c_str(), AVIO_FLAG_READ_WRITE))
{
qDebug() << "cannot open output file." << endl;
break;
}