学习如上链接,同时以ffmpeg 4.4 版本做相关实现,中间可能有一些差异和坑,在此记录。
本文实现了一个将输入的视频文件转换为一帧一帧的ppm 文件的过程。
基本概念
容器container,指定了视频信息存储的格式,常见的如avi,quicktime,flv
流streams,音频流,视频流,流,可以理解为,随着时间的推移提供的一系列数据元素,比如每秒可以获取30 帧的视频数据。
帧 frames,流里面的数据。每个frames 被不同的codec(编码器) 编码。
codec 定义了帧数据如何被编码和解码,比如 h264,h265等。
Packets(frames 被编码后的数据),是实际在stream中的数据。是可以包含被decoded成raw treams原始帧的数据片段,我们最终可以为我们的应用程序操作这些数据。
一般每个packets 包含一帧视频frames或者多个音频frames。
处理视频文件的基本流程:
1. 打开文件,找到容器格式
2. 找到stream,找到其中的编码方式
3. 从stream 中不断获取packet
4. 使用2 中找到的编码格式解码packet 最终得到每个frames
5. 重复到3
第一个程序是打开一个视频文件,之后将其中的视频流中的原始packet 保存到文件中。
下面会用到一些ffmpeg 常见的结构体,参考:
FFMPEG中最关键的结构体之间的关系_雷霄骅(leixiaohua1020)的专栏-CSDN博客_ffmpeg结构体
上面文章对ffmpeg 常见结构进行了简短精确的描述。推荐先看下
1. 打开文件
首先,av_register_all,这个函数4.4 版本已经被废弃了。会将所有可用的文件格式和编解码器注册到库中,以便在打开具有相应格式/编解码器的文件时自动使用它们,只需要调用一次。
之后打开文件
AVFormatContext *pFormatCtx = NULL; // Open video file if(avformat_open_input(&pFormatCtx, argv[1], NULL, 0, NULL)!=0) return -1; // Couldn't open file
argv[1] 对应文件名,这个函数读取文件头,并将得到的信息存储到avformatContext 结构体中。最后三个格式是指定一些额外的打开参数的,暂时不需要关心,将走默认配置。
这个函数只是负责打开文件头,之后需要检查文件中的stream 信息。
// Retrieve stream information if(avformat_find_stream_info(pFormatCtx, NULL)<0) return -1; // Couldn't find stream information
现在 pFormatCtx->streams 只是一个指针数组,大小为 pFormatCtx->nb_streams,所以让我们遍历它,直到找到视频流。
int videoStream = -1; for (int i = 0; i < avFormatContext->nb_streams; i++) if (avFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { videoStream = i; break; } if (videoStream == -1) return ; // Didn't find a video stream
原文中成员,比如codec已经被弃用了
int i; AVCodecContext *pCodecCtxOrig = NULL; AVCodecContext *pCodecCtx = NULL; // Find the first video stream videoStream=-1; for(i=0; i<pFormatCtx->nb_streams; i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) { videoStream=i; break; } if(videoStream==-1) return -1; // Didn't find a video stream // Get a pointer to the codec context for the video stream pCodecCtx=pFormatCtx->streams[videoStream]->codec;
2. 根据找到的streams 信息来找到正确的解码器,并初始化该编码器
原文中针对编码器的初始化动作已经不可用,下面是参考ffplay.c 中初始化得到的逻辑:
AVCodecContext* avCodecContext = avcodec_alloc_context3(NULL);
result = avcodec_parameters_to_context(avCodecContext, avFormatContext->streams[videoStream]->codecpar);
if (result < 0)
{
assert(false);
}
avCodecContext->pkt_timebase = avFormatContext->streams[videoStream]->time_base;
AVCodec* codec = avcodec_find_decoder(avCodecContext->codec_id);
avCodecContext->codec_id = codec->id;
3. 实际存储视频帧。
我们最终的目的是将原始视频帧存储为24-bit RGB 视频。
AVFrame* pFrame = nullptr;
pFrame = av_frame_alloc();
// 我们最终的目的是将原始视频帧存储为24-bit RGB 视频。
AVFrame* pFrameRGB24 = av_frame_alloc();
uint8_t* bufferRawRGB24 = nullptr;
const int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGB24, avCodecContext->width, avCodecContext->height, 1);
bufferRawRGB24 = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t));
av_image_fill_arrays(pFrameRGB24->data, pFrameRGB24->linesize, bufferRawRGB24, AV_PIX_FMT_RGB24, avCodecContext->width, avCodecContext->height, 1);
av_malloc 是 ffmpeg 的 malloc,它只是 malloc 的一个简单包装器,可确保内存地址对齐等。它不会保护您免受内存泄漏、双重释放或其他 malloc 问题的影响。
现在我们使用 avpicture_fill 将帧与我们新分配的缓冲区相关联。关于 AVPicture 演员表: AVPicture 结构是 AVFrame 结构的子集 - AVFrame 结构的开头与 AVPicture 结构相同。这里改成了av_image_fill_arrays ,av_image_fill_arrays 参考:av_image_fill_arrays详解_longjiang321的博客-CSDN博客
4. 读取并保存
我们要做的是通过读取数据包来读取整个视频流,将其解码为我们的帧,一旦我们的帧完成,我们将转换并保存它。
// 读取数据
// sws_ctx 定义了从pix_fmt 到 AV_PIX_FMT_RGB24的转换
struct SwsContext* sws_ctx = NULL;
int frameFinished;
// initialize SWS context for software scaling
sws_ctx = sws_getContext(avCodecContext->width,
avCodecContext->height,
avCodecContext->pix_fmt,
avCodecContext->width,
avCodecContext->height,
AV_PIX_FMT_RGB24,
SWS_BILINEAR,
NULL,
NULL,
NULL
);
int i = 0;
AVPacket packet;
bool bReadEof = false;
while (true)
{
int readResult = -1;
if (!bReadEof)
{
readResult = av_read_frame(avFormatContext, &packet);
if (readResult < 0) {
::MessageBoxA(0, 0, GetFFmpegErorString(readResult).c_str(), 0);
bReadEof = true;
}
else if (readResult == 0) {
static int iCnt = 0;
if (packet.stream_index == videoStream) {
++iCnt;
}
CString str;
str.Format(L"cunt[%d]\r\n", iCnt);
OutputDebugStringW(str.GetBuffer());
}
}
if (bReadEof)
{
// 需要给刷空
avcodec_send_packet(avCodecContext, NULL);
}
else
{
// Is this a packet from the video stream?
if (packet.stream_index == videoStream) {
// Decode video frame
avcodec_send_packet(avCodecContext, &packet);
}
}
int receiveResult = avcodec_receive_frame(avCodecContext, pFrame);
// Did we get a video frame?
if (receiveResult == 0) {
// Convert the image from its native format to RGB
sws_scale(sws_ctx, (uint8_t const* const*)pFrame->data,
pFrame->linesize, 0, avCodecContext->height,
pFrameRGB24->data, pFrameRGB24->linesize);
++i;
SaveFrame(pFrameRGB24, avCodecContext->width,
avCodecContext->height, i);
}
else if (receiveResult == AVERROR_EOF)
{
::MessageBoxA(0, 0, "read eof", 0);
break;
}
else if(receiveResult == AVERROR(EAGAIN)){
if (bReadEof) {
break;
}
else {
}
}
else {
msgBoxFFmpegError(receiveResult);
}
// Free the packet that was allocated by av_read_frame
if(readResult == 0)
av_packet_unref(&packet);
}
清理
完整代码
// MFCAudioResampleDlg.cpp: 实现文件
//
#include "pch.h"
#include "framework.h"
#include "MFCAudioResample.h"
#include "MFCAudioResampleDlg.h"
#include "afxdialogex.h"
extern "C"
{
#include <libswresample/swresample.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
}
std::string GetFFmpegErorString(int errnum)
{
static CHAR g_av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 };
return std::string(av_make_error_string(g_av_error, AV_ERROR_MAX_STRING_SIZE, errnum));
}
void msgBoxFFmpegError(int errnum)
{
::MessageBoxA(0, 0, GetFFmpegErorString(errnum).c_str(), 0);
}
std::wstring GetOneFile(BOOL bOpen = TRUE)
{
CString FilePathName;
CFileDialog dlg(bOpen, NULL, NULL, NULL, NULL);//TRUE为OPEN对话框,FALSE为SAVE AS对话框
if (dlg.DoModal() == IDOK) {
//清空
FilePathName = dlg.GetPathName();
}
return std::wstring(FilePathName.GetBuffer());
}
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CMFCAudioResampleDlg 对话框
CMFCAudioResampleDlg::CMFCAudioResampleDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_MFCAUDIORESAMPLE_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFCAudioResampleDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_INPUT_FILE, m_targetFilePath);
}
BEGIN_MESSAGE_MAP(CMFCAudioResampleDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_CHOOSE_FILE, &CMFCAudioResampleDlg::OnBnClickedButtonChooseFile)
END_MESSAGE_MAP()
// CMFCAudioResampleDlg 消息处理程序
BOOL CMFCAudioResampleDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CMFCAudioResampleDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CMFCAudioResampleDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CMFCAudioResampleDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void SaveFrame(AVFrame* pFrame, int width, int height, int iFrame) {
FILE* pFile;
char szFilename[32];
int y;
// Open file
sprintf(szFilename, "frame%d.ppm", iFrame);
pFile = fopen(szFilename, "wb");
if (pFile == NULL)
return;
// Write header
fprintf(pFile, "P6\n%d %d\n255\n", width, height);
// Write pixel data
for (y = 0; y < height; y++)
fwrite(pFrame->data[0] + y * pFrame->linesize[0], 1, width * 3, pFile);
// Close file
fclose(pFile);
}
void CMFCAudioResampleDlg::OnBnClickedButtonChooseFile()
{
// TODO: 在此添加控件通知处理程序代码
auto target = GetOneFile();
m_targetFilePath.SetWindowTextW(target.c_str());
UpdateData(TRUE);
CString strTargetWindowText;
m_targetFilePath.GetWindowTextW(strTargetWindowText);
AVFormatContext* avFormatContext = avformat_alloc_context();
USES_CONVERSION;
if (!PathFileExists(strTargetWindowText.GetBuffer())) {
return;
}
auto result = avformat_open_input(&avFormatContext, W2A((strTargetWindowText.GetBuffer())), nullptr, nullptr);
if (result < 0) {
assert(false);
}
result = avformat_find_stream_info(avFormatContext, NULL);
if (result < 0)
{
assert(false);
}
av_dump_format(avFormatContext, 0, NULL, 0);
// Find the first video stream
int videoStream = -1;
for (int i = 0; i < avFormatContext->nb_streams; i++)
if (avFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStream = i;
break;
}
if (videoStream == -1)
return ; // Didn't find a video stream
AVCodecContext* avCodecContext = avcodec_alloc_context3(NULL);
result = avcodec_parameters_to_context(avCodecContext, avFormatContext->streams[videoStream]->codecpar);
if (result < 0)
{
assert(false);
}
avCodecContext->pkt_timebase = avFormatContext->streams[videoStream]->time_base;
AVCodec* codec = avcodec_find_decoder(avCodecContext->codec_id);
avCodecContext->codec_id = codec->id;
result = avcodec_open2(avCodecContext, codec, nullptr);
if (result < 0)
{
msgBoxFFmpegError(result);
assert(false);
}
AVFrame* pFrame = nullptr;
pFrame = av_frame_alloc();
// 我们最终的目的是将原始视频帧存储为24-bit RGB 视频。
AVFrame* pFrameRGB24 = av_frame_alloc();
uint8_t* bufferRawRGB24 = nullptr;
const int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGB24, avCodecContext->width, avCodecContext->height, 1);
bufferRawRGB24 = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t));
av_image_fill_arrays(pFrameRGB24->data, pFrameRGB24->linesize, bufferRawRGB24, AV_PIX_FMT_RGB24, avCodecContext->width, avCodecContext->height, 1);
// 读取数据
// sws_ctx 定义了从pix_fmt 到 AV_PIX_FMT_RGB24的转换
struct SwsContext* sws_ctx = NULL;
int frameFinished;
// initialize SWS context for software scaling
sws_ctx = sws_getContext(avCodecContext->width,
avCodecContext->height,
avCodecContext->pix_fmt,
avCodecContext->width,
avCodecContext->height,
AV_PIX_FMT_RGB24,
SWS_BILINEAR,
NULL,
NULL,
NULL
);
int i = 0;
AVPacket packet;
bool bReadEof = false;
while (true)
{
int readResult = -1;
if (!bReadEof)
{
readResult = av_read_frame(avFormatContext, &packet);
if (readResult < 0) {
::MessageBoxA(0, 0, GetFFmpegErorString(readResult).c_str(), 0);
bReadEof = true;
}
else if (readResult == 0) {
static int iCnt = 0;
if (packet.stream_index == videoStream) {
++iCnt;
}
CString str;
str.Format(L"cunt[%d]\r\n", iCnt);
OutputDebugStringW(str.GetBuffer());
}
}
if (bReadEof)
{
// 需要给刷空
avcodec_send_packet(avCodecContext, NULL);
}
else
{
// Is this a packet from the video stream?
if (packet.stream_index == videoStream) {
// Decode video frame
avcodec_send_packet(avCodecContext, &packet);
}
}
int receiveResult = avcodec_receive_frame(avCodecContext, pFrame);
// Did we get a video frame?
if (receiveResult == 0) {
// Convert the image from its native format to RGB
sws_scale(sws_ctx, (uint8_t const* const*)pFrame->data,
pFrame->linesize, 0, avCodecContext->height,
pFrameRGB24->data, pFrameRGB24->linesize);
++i;
SaveFrame(pFrameRGB24, avCodecContext->width,
avCodecContext->height, i);
}
else if (receiveResult == AVERROR_EOF)
{
::MessageBoxA(0, 0, "read eof", 0);
break;
}
else if(receiveResult == AVERROR(EAGAIN)){
if (bReadEof) {
break;
}
else {
}
}
else {
msgBoxFFmpegError(receiveResult);
}
// Free the packet that was allocated by av_read_frame
if(readResult == 0)
av_packet_unref(&packet);
}
av_frame_free(&pFrame);
av_frame_free(&pFrameRGB24);
av_free(bufferRawRGB24);
avcodec_close(avCodecContext);
avformat_close_input(&avFormatContext);
}
完整工程: