FFmpeg是一个免费开源的音视频处理工具库,可以实现音视频格式转换、编解码、流媒体处理等功能。它由多个开源组件组成,包括libavcodec(音视频编解码器)、libavformat(封装格式处理库)、libavfilter(音视频滤镜库)等等。因为其可移植性好、功能强大和代码简单易于维护等优势,FFmpeg被广泛应用于流媒体、多媒体播放器、视频编辑软件、视频会议、直播等领域。
FFmpeg支持的视频格式包括MPEG4、AVI、WMV、FLV、H.264等等,支持的音频格式包括MP3、WMA、AAC、AMR等等。除此之外,FFmpeg还可以通过FFserver搭建流媒体服务器,支持RTSP、RTMP等传输协议。FFmpeg也提供了一些命令行工具,如ffmpeg、ffplay等,用于快速对音视频文件进行转换和播放。
FFmpeg的使用虽然相对复杂,但是相应的API文档和丰富的社区支持,加上其强大的功能,使得它成为众多开发者和视频爱好者的首选工具之一。
FFmpeg被广泛应用于流媒体、多媒体播放器、视频编辑软件、视频会议、直播等领域。它可以用来:
FFmpeg库采用模块化设计,整体架构分为以下几个模块:
在FFmpeg库中,每个模块都是相对独立的,可以单独使用也可以互相配合使用,使得各个模块之间的调用和扩展更加容易。例如,我们可以通过libavcodec模块进行音视频的编解码,再通过libavformat模块进行封装格式的处理,最终通过libswscale模块进行视频的缩放和转换,并输出到目标文件中。
简单来说,它的流程大致分为以下几步:
FFmpeg API提供了大量的音视频处理函数和接口,主要包括以下几个方面:
以下是一个基于WPF的简单案例,演示了如何使用FFmpeg库来将一个视频文件转换为另一个格式的视频文件:
using (var videoReader = new VideoFileReader())
{
videoReader.Open(@"C:\Videos\input.mp4");
using (var videoWriter = new VideoFileWriter())
{
var outputFilePath = @"C:\Videos\output.avi";
var codec = "msmpeg4v3";
videoWriter.Open(outputFilePath, videoReader.Width, videoReader.Height, videoReader.FrameRate, VideoCodec.FromFourCC(codec));
var currentFrame = new VideoFrame(videoReader.Width, videoReader.Height);
while (videoReader.ReadVideoFrame(currentFrame))
{
videoWriter.WriteVideoFrame(currentFrame);
}
}
}
以下是使用WPF编写一个视频解码的案例代码:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Threading.Tasks;
using FFmpeg.AutoGen;
namespace VideoDecoderDemo
{
public partial class MainWindow : Window
{
private AVFormatContext* pFormatCtx = null;
private int videoStreamIndex = -1;
private AVCodecContext* pCodecCtx = null;
private AVCodec* pCodec = null;
private AVFrame* pFrame = null;
private AVPacket* pPacket = null;
private AVPixelFormat sourcePixelFormat;
private AVPixelFormat destinationPixelFormat;
private IntPtr imgDataPtr = IntPtr.Zero;
private int imgLineSize = 0;
private Task decodingTask;
private bool isDecoding = false;
public MainWindow()
{
InitializeComponent();
}
private void OpenFileButton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".mp4";
dlg.Filter = "Video Files (*.mp4;*.avi;*.mkv)|*.mp4;*.avi;*.mkv|All Files (*.*)|*.*";
Nullable result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
OpenVideoFile(filename);
}
}
private void PlayButton_Click(object sender, RoutedEventArgs e)
{
if (!isDecoding)
{
StartDecoding();
PlayButton.Content = "停止播放";
}
else
{
StopDecoding();
PlayButton.Content = "开始播放";
}
}
private unsafe void OpenVideoFile(string filename)
{
// 初始化FFmpeg库
ffmpeg.av_register_all();
// 打开视频文件
int ret = ffmpeg.avformat_open_input(&pFormatCtx, filename, null, null);
if (ret < 0)
{
MessageBox.Show("打开视频文件失败:" + System.Runtime.InteropServices.Marshal.PtrToStringAnsi((IntPtr)ffmpeg.av_err2str(ret)));
return;
}
// 获取视频流信息
ret = ffmpeg.avformat_find_stream_info(pFormatCtx, null);
if (ret < 0)
{
MessageBox.Show("获取视频流信息失败:" + System.Runtime.InteropServices.Marshal.PtrToStringAnsi((IntPtr)ffmpeg.av_err2str(ret)));
return;
}
// 查找视频流索引
for (int i = 0; i < pFormatCtx->nb_streams; i++)
{
if (pFormatCtx->streams[i]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO)
{
videoStreamIndex = i;
break;
}
}
if (videoStreamIndex == -1)
{
MessageBox.Show("没有找到视频流");
return;
}
// 获取视频解码器
pCodecCtx = pFormatCtx->streams[videoStreamIndex]->codec;
pCodec = ffmpeg.avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == null)
{
MessageBox.Show("找不到视频解码器");
return;
}
// 打开视频解码器
ret = ffmpeg.avcodec_open2(pCodecCtx, pCodec, null);
if (ret < 0)
{
MessageBox.Show("打开视频解码器失败:" + System.Runtime.InteropServices.Marshal.PtrToStringAnsi((IntPtr)ffmpeg.av_err2str(ret)));
return;
}
// 分配解码后数据的结构体
pFrame = ffmpeg.av_frame_alloc();
// 分配解码前数据的结构体
pPacket = ffmpeg.av_packet_alloc();
if (pPacket == null)
{
MessageBox.Show("分配AVPacket结构体失败");
return;
}
// 获取视频像素格式
sourcePixelFormat = pCodecCtx->pix_fmt;
if (sourcePixelFormat == AVPixelFormat.AV_PIX_FMT_NONE)
{
MessageBox.Show("找不到视频像素格式");
return;
}
// 设置要转换后的像素格式
destinationPixelFormat = AVPixelFormat.AV_PIX_FMT_BGR24;
// 计算转换后每行图像数据所占的字节数
int bytesPerLine = ffmpeg.av_image_get_linesize(destinationPixelFormat, pCodecCtx->width, 0);
// 分配转换后的图像数据空间
imgDataPtr = (IntPtr)ffmpeg.av_malloc((ulong)bytesPerLine * pCodecCtx->height);
// 创建Bitmap并显示
BitmapSource bitmapSource = BitmapSource.Create(pCodecCtx->width, pCodecCtx->height, 96, 96, System.Windows.Media.PixelFormats.Bgr24, null, imgDataPtr, bytesPerLine * pCodecCtx->height, bytesPerLine);
VideoImage.Source = bitmapSource;
}
private void StartDecoding()
{
isDecoding = true;
decodingTask = new Task(() =>
{
while (isDecoding && ffmpeg.av_read_frame(pFormatCtx, pPacket) >= 0)
{
if (pPacket->stream_index == videoStreamIndex)
{
int ret = ffmpeg.avcodec_send_packet(pCodecCtx, pPacket);
if (ret < 0)
{
break;
}
while (ffmpeg.avcodec_receive_frame(pCodecCtx, pFrame) == 0)
{
// 创建SwScale上下文
SwsContext* swsctx = ffmpeg.sws_getContext(
pFrame->width,
pFrame->height,
sourcePixelFormat,
pFrame->width,
pFrame->height,
destinationPixelFormat,
ffmpeg.SWS_BICUBIC,
null,
null,
null);
// 执行像素格式转换
ffmpeg.sws_scale(swsctx, pFrame->data, pFrame->linesize, 0, pFrame->height, &imgDataPtr, &imgLineSize);
// 释放SwScale上下文
ffmpeg.sws_freeContext(swsctx);
Dispatcher.Invoke(() =>
{
// 创建Bitmap并显示
BitmapSource bitmapSource = BitmapSource.Create(pCodecCtx->width, pCodecCtx->height, 96, 96, System.Windows.Media.PixelFormats.Bgr24, null, imgDataPtr, imgLineSize * pCodecCtx->height, imgLineSize);
VideoImage.Source = bitmapSource;
});
}
}
// 释放AVPacket的缓冲区
ffmpeg.av_packet_unref(pPacket);
}
StopDecoding();
// 释放内存
if (imgDataPtr != IntPtr.Zero)
{
ffmpeg.av_free(imgDataPtr);
imgDataPtr = IntPtr.Zero;
}
if (pPacket != null)
{
ffmpeg.av_packet_free(&pPacket);
pPacket = null;
}
if (pFrame != null)
{
ffmpeg.av_frame_free(&pFrame);
pFrame = null;
}
if (pCodecCtx != null)
{
ffmpeg.avcodec_close(pCodecCtx);
pCodecCtx = null;
}
if (pFormatCtx != null)
{
ffmpeg.avformat_close_input(&pFormatCtx);
pFormatCtx = null;
}
});
decodingTask.Start();
}
private void StopDecoding()
{
isDecoding = false;
if (decodingTask != null && !decodingTask.IsCompleted)
{
decodingTask.Wait();
}
}
}
}
该代码使用FFmpeg进行视频解码,并将解码后的图像显示在WPF的Image控件上。其中,OpenFileButton_Click函数用于打开视频文件;PlayButton_Click函数用于开始/停止播放视频;StartDecoding函数和StopDecoding函数用于控制解码的开始和结束。在OpenVideoFile函数中,我们需要先打开视频文件,获取视频流信息,查找视频流索引,获取视频解码器,打开视频解码器,并分配解码前后数据的内存空间。在StartDecoding函数中,我们使用了两个FFmpeg函数:av_read_frame和avcodec_receive_frame来获取解码前和解码后的数据。在这些函数调用中,我们执行了像素格式转换,并将转换后的图像数据显示在Image控件上。最后,在StopDecoding函数中,我们释放所有使用的FFmpeg内存空间,并关闭解码器和视频文件。
FFmpeg是一个功能强大的音视频处理库,它可以实现多种音视频格式的编解码、转换和处理。虽然学习曲线较陡峭,但是其文档和教程较为丰富,易于学习。在一定的场景下,使用FFmpeg可以大幅简化音视频处理的开发难度和工作量。