技术标签: 音视频 机器视觉+图像处理+数字信号处理 ffmpeg
本文参考了雷博士的博客:
最简单的基于FFMPEG+SDL的视频播放器:拆分-解码器和播放器
基本上雷博士这篇博客已经把这个问题讲的挺清楚了。但是 ffmpeg 新版本的 API 有变化,这篇博客的代码已经无法直接编译运行。所以我写了今天这篇博客,用 新的 API 实现了视频解码的功能。
雷博士的代码除了视频解码还有音频解码,同时还利用 SDL 把视频显示出来了。 我觉得作为初学者还是每次学习的内容不要太多。既然我们的重点是视频解码,那就用最精简的代码来实现视频解码。这样我们的学习曲线才不会太陡峭。
前面几篇博客讲解了 libavformat 和 libswscale 这两个库的使用方法。所以这篇博客里不会再讲解相应的代码功能。如果有同学对我代码里涉及这两个库的用法不明白,可以先读读我的前几篇博客:
libavcodec 的核心是 AVCodec 和 AVCodecContext。AVCodec 是具体的编解码器,AVCodecContext 则是编解码时所需的上下文环境。一个 AVStream 要对应一个AVCodecContext,一个 AVCodecContext 要关联上一个 AVCodec 。实际使用时有可能会有多个 AVCodecContext 关联同一个 AVCodec 的情况。尤其是我们解码音频的时候。比如我们的音频文件时 5.1声道的。通常会对应 3 个 AVStream。左右声道在一个 AVStream 里,环绕声在一个 AVStream,最后低音在另一个AVStream。 3 个AVStream的编码可能是相同的。那么我们要解码这个音频文件时就应该建立 3 个 AVCodecContext ,分别对应三个 AVStream。然后只需要有 1 个 AVCodec 。每个 AVCodecContext 都利用这一个 AVCodec 来解码。
上面是以音频解码为例,实际上视频解码也可能是这样的。比如我们有一个 3D 视频,里面就会有 2 个视频 AVStream,分别对应我们左眼和右眼看到的图像。这两个视频通常编码格式是相同的,所以可以公用一个 AVCodec 。但是一定要用两个 AVCodecContext 。
下面是解码前的准备工作,先要生成 AVCodec 和 AVCodecContext 的实例并打开。
AVCodecParameters * codecpar = pFormatCtx->streams[0]->codecpar;
AVCodec *pCodec = avcodec_find_decoder(codecpar->codec_id);
if(pCodec == nullptr) qWarning() << "Cannot find_decoder";
AVCodecContext *pCodecCtx = avcodec_alloc_context3(pCodec);
if(pCodecCtx == nullptr) qWarning() << "Cannot alloc pCodecCtx";
avcodec_parameters_to_context(pCodecCtx, codecpar);
if(avcodec_open2(pCodecCtx, pCodec, nullptr) < 0)
{
printf("Could not open AVCodec.\n");
exit(1);
}
到这里Codec 就建好了。所谓解码就是把一个 AVPacket 中的数据解成 AVFrame。简单的说 AVFrame 是原始的,没有编码、没有压缩的数据,编码压缩之后的数据叫做 AVPacket 。
那么,一个 AVPacket 是对应一个 AVFrame 吗?从逻辑上讲是这样的,但是实际上,经常我们有了一个 AVPacket ,却并不能当时就解出 AVFrame 来。因为我们知道视频帧 分为 I帧,P帧和 B 帧。如果 一个 AVPacket 里面的数据是 I帧 那么我们就可以直接解出 AVFrame 。P帧 需要参考前一帧的数据,B 帧还需要有后一帧的数据才能解码。所以我们会遇到前几个 AVPacket 解不出数据。到了某个 AVPacket ,可以连续解出多个 AVFrame 来的情况。这时这 多个 AVFrame 就包括前面积压的 AVPacket 里的数据。
在旧版 FFMPEG 中,是用下面这个函数来解码。
int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
int *got_picture_ptr,
const AVPacket *avpkt);
这里 got_picture_ptr 就是标明是否可以从当前帧解出 AVFrame。
下面的代码片段来自雷博士的博客:https://blog.csdn.net/leixiaohua1020/article/details/46889389
这个代码给出了一个解码的框架。
while(av_read_frame(pFormatCtx, packet) >=0 )
{
if(packet->stream_index == videoindex)
{
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
if(ret < 0)
{
printf("Decode Error.\n");
return -1;
}
if(got_picture)
{
// 到这里表示成功解出一个 Frame,可以用这个 Frame 中的数据做我们正式的工作了
printf("Flush Decoder: Succeed to decode 1 frame!\n");
}
}
av_free_packet(packet);
}
//flush decoder
//FIX: Flush Frames remained in Codec
while (1)
{
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
if (ret < 0)
break;
if (!got_picture)
break;
// 到这里表示成功解出一个 Frame,可以用这个 Frame 中的数据做我们正式的工作了
printf("Flush Decoder: Succeed to decode 1 frame!\n");
}
这个代码里后面多了一个 while() 循环,就是解决 Codec 中积存的 Frame 问题。
我个人猜测,可能就是由于解码代码中必须要多这一段,让人总感觉这代码不那么清爽。所以 ffmpeg 的作者才把 avcodec_decode_video2() 函数给废弃了的。我们的新代码中应该使用如下两个函数:
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt);
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame);
简单的说这两个函数就是解决了 avcodec_decode_video2() 函数强制要求 Packet 和 Frame 一对一的问题。让我们可以往Codec 推一个 Packet ,然后读出多个 frame 来。当然,这多个 frame 并不是真的是从这个 packet 里解出来的,还可能包括以前推到 Codec 里的其他 packet 的的数据。
新版的这两个函数的用法可以参考 ffmpeg 自带的例子代码 demuxing_decoding.c。 代码片段如下:
while (av_read_frame(fmt_ctx, pkt) >= 0) {
// check if the packet belongs to a stream we are interested in, otherwise
// skip it
if (pkt->stream_index == video_stream_idx)
ret = decode_packet(video_dec_ctx, pkt);
else if (pkt->stream_index == audio_stream_idx)
ret = decode_packet(audio_dec_ctx, pkt);
av_packet_unref(pkt);
if (ret < 0)
break;
}
解码操作集中在 decode_packet() 函数中了,调用一次 avcodec_send_packet() 将一个 packet 推给Codec,然后 调用一次或多次 avcodec_receive_frame() 来获得 frame:
static int decode_packet(AVCodecContext *dec, const AVPacket *pkt)
{
int ret = 0;
// submit the packet to the decoder
ret = avcodec_send_packet(dec, pkt);
if (ret < 0) {
fprintf(stderr, "Error submitting a packet for decoding (%s)\n", av_err2str(ret));
return ret;
}
// get all the available frames from the decoder
while (ret >= 0) {
ret = avcodec_receive_frame(dec, frame);
if (ret < 0) {
// those two return values are special and mean there is no output
// frame available, but there were no errors during decoding
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
return 0;
fprintf(stderr, "Error during decoding (%s)\n", av_err2str(ret));
return ret;
}
// write the frame data to output file
if (dec->codec->type == AVMEDIA_TYPE_VIDEO)
ret = output_video_frame(frame);
else
ret = output_audio_frame(frame);
av_frame_unref(frame);
if (ret < 0)
return ret;
}
return 0;
}
仿照这个代码,我做了一个小例子,这个小例子中,我将视频帧存到图像文件中。当然,一个视频文件的帧数很多,全都存文件太占硬盘空间了。所以我是每隔 10 帧存一幅图像。并且也不是从视频的开始就存,而是 seek 到了一个比较靠后的地方。存图像这个操作我用到了 Qt 的 QImage 类。没有用过 Qt 的同学可以忽略那一两行代码。不过Qt 真的很好用,建议有点 C++ 基础的同学都可以学学。
void save(AVFrame *pFrame, int frameCount)
{
int srcWidth = pFrame->width;
int srcHeight = pFrame->height;
AVPixelFormat srcFormat = (AVPixelFormat)pFrame->format;
struct SwsContext *imageConvertContex = sws_getContext(srcWidth, srcHeight, srcFormat,
srcWidth, srcHeight, AV_PIX_FMT_RGB24,
SWS_BICUBIC, nullptr, nullptr, nullptr);
QImage image(srcWidth, srcHeight, QImage::Format_RGB888);
uint8_t *out_data[1];
int out_linesize[1];
av_image_fill_arrays(out_data, out_linesize, image.bits(), AV_PIX_FMT_RGB24, srcWidth, srcHeight, 1);
//转格式
sws_scale(imageConvertContex,
pFrame->data, pFrame->linesize, 0, srcHeight,
out_data, out_linesize);
if(imageConvertContex) sws_freeContext(imageConvertContex);
QString fileName = QString("d:/AV_%1.jpg").arg(frameCount);
image.save(fileName);
}
int decode_packet(AVCodecContext *dec, const AVPacket *pkt, AVFrame *pFrame)
{
static int frameCount = 0;
int ret = 0;
//avcodec_decode_video2();
// submit the packet to the decoder
ret = avcodec_send_packet(dec, pkt);
if (ret < 0) {
//fprintf(stderr, "Error submitting a packet for decoding (%s)\n", av_err2str(ret));
return ret;
}
// get all the available frames from the decoder
while (ret >= 0) {
ret = avcodec_receive_frame(dec, pFrame);
if (ret < 0) {
// those two return values are special and mean there is no output
// frame available, but there were no errors during decoding
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
return 0;
//fprintf(stderr, "Error during decoding (%s)\n", av_err2str(ret));
return ret;
}
frameCount ++;
// write the frame data to output file
if(frameCount % 10 == 1)
{
qDebug() <<(AVPixelFormat) pFrame->format << ", packetCount = " << packetCount << ", frameCount = " << frameCount;
save(pFrame, frameCount);
}
av_frame_unref(pFrame);
}
return 0;
}
void test03()
{
const char * filename = "D:\\AV36_1.avi";
AVFormatContext *pFormatCtx = avformat_alloc_context();
msg("avformat_open_input",
avformat_open_input(&pFormatCtx, filename, nullptr, nullptr));
msg("avformat_find_stream_info",
avformat_find_stream_info(pFormatCtx, nullptr));
av_dump_format(pFormatCtx, 0, filename, 0);
AVCodecParameters * codecpar = pFormatCtx->streams[0]->codecpar;
AVCodec *pCodec = avcodec_find_decoder(codecpar->codec_id);
if(pCodec == nullptr) qWarning() << "Cannot find_decoder";
AVCodecContext *pCodecCtx = avcodec_alloc_context3(pCodec);
if(pCodecCtx == nullptr) qWarning() << "Cannot alloc pCodecCtx";
avcodec_parameters_to_context(pCodecCtx, codecpar);
if(avcodec_open2(pCodecCtx, pCodec, nullptr) < 0)
{
printf("Could not open AVCodec.\n");
exit(1);
}
av_seek_frame(pFormatCtx, -1, 30 * AV_TIME_BASE, AVSEEK_FLAG_BACKWARD);
AVPacket pkt;
while (1)
{
int ret = av_read_frame(pFormatCtx, &pkt);
if (ret < 0) break;
if (pkt.stream_index != 0)
{
av_packet_unref(&pkt);
continue;
}
AVFrame *pFrame = av_frame_alloc();
AVFrame *pFrameRGB32 = av_frame_alloc();
packetCount++;
decode_packet(pCodecCtx, &pkt, pFrame);
av_frame_free(&pFrameRGB32);
av_frame_free(&pFrame);
av_packet_unref(&pkt);
}
avformat_close_input(&pFormatCtx);
}
输出结果如下,总共保存了 5 张图片:
avformat_open_input : success.
avformat_find_stream_info : success.
Input #0, avi, from 'D:\AV36_1.avi':
Duration: 00:00:32.93, start: 0.000000, bitrate: 2372 kb/s
Stream #0:0: Video: indeo5 (IV50 / 0x30355649), yuv410p, 320x240, 2058 kb/s, 15 fps, 15 tbr, 15 tbn, 15 tbc
Metadata:
title : Steyr.avi ���#1
Stream #0:1: Audio: adpcm_ms ([2][0][0][0] / 0x0002), 22050 Hz, 2 channels, s16, 176 kb/s
Metadata:
title : Sound Forge 4.0 Audio
AV_PIX_FMT_YUV410P, packetCount = 1, frameCount = 1
AV_PIX_FMT_YUV410P, packetCount = 11, frameCount = 11
AV_PIX_FMT_YUV410P, packetCount = 21, frameCount = 21
AV_PIX_FMT_YUV410P, packetCount = 31, frameCount = 31
AV_PIX_FMT_YUV410P, packetCount = 41, frameCount = 41
好了,这一讲就讲这么多。下一篇博客准备将这篇博客的内容用 C++ 来封装一下。封装之后的代码会极度的清爽。请大家拭目以待。
文章浏览阅读1.3k次。EasyClick 日志悬浮窗修改_easyclick 实时更改悬浮窗文本
文章浏览阅读1.4k次。1.APP端使用Retrofit传输图片 RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part filePart = MultipartBody.Part.createFormD..._multipartfile file 为空时报错
文章浏览阅读1.9w次,点赞39次,收藏69次。Windows TerminalCommand Prompt, PowerShell & Windows Terminal安装Windows Terminal在 Windows 终端中设置 Powerline毛玻璃玻璃主题过程中遇到的问题:警告: git command could not be found. Please create an alias or add it to your PATHSet-Theme : 无法将“Set-Theme”项识别为 cmdlet、函数、脚本文件或可运行程序_oh-my-posh
文章浏览阅读1k次。文章目录手工配置静态lacp三层链路聚合手工配置这里只有200M,即使SW5有2G,但是实际只能转发200M。静态lacpSW5同理lacp有差错校验的效果。三条链路1:1:1,最大活跃是8。将其中一条链路作为备份。记住两边都需要修改假如我们将0/0/1down掉,实现备份效果。将SW5和SW6也修改:需要先删掉原先的。这是有问题的。不知道是模拟器问题还是说在真机操作的时候是配不了。按理两端会自动协商。三层链路聚合如果要在路由器上配置_ensp链路聚合实验总结心得
文章浏览阅读279次。onewindows系统是我百度能力弱吗?安装了一大推东西,依旧搞不好…能够解决的大神,留言留言!!!谢谢谢谢谢…twoselsenium对于这个问题我也是…驱动和谷歌的版本是一样的环境变量也加了,驱动地址,谷歌地址该给的都给了,仍然…同样,可以解决的小伙伴,留个言吧,拜托拜托这些bug不经意间毁掉了我好多的爬虫乐趣哎…..._opendiseaseinfocommonqueryyc0102 is not defined
文章浏览阅读2.3k次。老猿Python博文目录老猿Python博客地址showGrid属性用于控制视图中数据项之间是否显示网格,如果该属性为True,则绘制网格;如果该属性为False,则不绘制网格。showGrid属性默认值为True,可以通过showGrid() 和setShowGrid(bool show)来访问或设置该属性。老猿Python,跟老猿学Python! 博文目录 博客地址..._setshowgrid
文章浏览阅读1.1k次。版本及下载地址:组件版本下载地址tomcat9.0.41https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-9/v9.0.41/bin/apache-tomcat-9.0.41.tar.gzoracle-ee19c见下文apex20.2http://www.oracle.com/technetwork/developer-tools/apex/downloads/index.htmlor._oracle 19c apex
文章浏览阅读560次。进入到公众号应用后第三方页面后会出现的 redirect_uri 参数错误未配置可信域名 , 无法进行网页授权OAuth2接口认证 , 配置可信域名即可_redirect_url未登记可信域名
文章浏览阅读10w+次,点赞94次,收藏315次。 由于在学习中,我们经常会用到别人已经开发好的某些项目,要学习别人的东西,你肯定的先导入编辑器中自己试试吧,eclipse大家都会,可是换成idea开发又该怎样导入呢?整合最近我已需要学习别人的项目,希望把这个过程记录下来帮助大家学习.那么我们就开始吧第二步找到自己要导入的项目,然后点击ok 如果是maven就选择maven剩下的你就一路点击next就ok,最..._idea导入新的项目
文章浏览阅读395次。点击上方“阿拉奇学Java”,选择“置顶或者星标”每天早晨00点00分,与你相约!往日回顾:一款vue编写的功能强大的swagger-ui,有点秀(附开源地址)富 Web 时代,应用变..._docker深度学习傻瓜教程
文章浏览阅读3.4k次,点赞2次,收藏3次。android应用的so文件路径修改因为某些原因,系统应用的so文件没能正常加载,应用无法正常打开。所以这时需要应用自行释放so文件在自己的包路径下。我对这种情况有一个自己的解决方案。下面我介绍下我的方案与代码与大家分享。_android 对applicationinfo.sourcedir修改
文章浏览阅读628次。之前集成别人的一个项目,发现了一个挺好用的查找文件的功能,路径我这边选择的内部存储:Environment.getExternalStorageDirectory().getAbsolutePath();我们看效果图: 一个很简单的选择弹窗,我们看一下代码: 放在openFileDialog方法中,在需要的地方调用即可..._android 选中sdcard 某个文件必须弹框