ffmpeg和Opencv结合进行视频解码播放
2015-06-25 21:43
519 查看
引子
OpenCV中有自己的用于处理图片和视频的类VideoCapture,可以很方便的读入文件和显示。现在视频数据流是ffmpeg解码h264文件得到的,由于要依赖该数据源进行相应的后续处理,所以需要将ffmpeg中得到的数据缓存转换成可以被OpenCV处理的Mat类对象。
ffmpeg介绍
FFmpeg是一个开源免费跨平台的视频和音频流方案,属于自由软件,采用LGPL或GPL许可证(依据你选择的组件)。它提供了录制、转换以及流化音视频的完整解决方案。它包含了非常先进的音频/视频编解码库libavcodec,为了保证高可移植性和编解码质量,libavcodec里很多codec都是从头开发的。FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。它包括了目前领先的音/视频编码库libavcodec。 FFmpeg是在Linux下开发出来的,但它可以在包括Windows在内的大多数操作系统中编译。
FFmpeg的组成结构
FFmpeg主要由一下几个部分组成:libavcodec:一个包含了所有FFmpeg音视频编解码器的库。 为了保证最优性能和高可复用性,大多数编解码器从头开发的。
libavformat:一个包含了所有的普通音视格式的解析器和 产生器的库。
三个实例程序,这三个实例较为复杂,基本可以作为API使用手册:
ffmpeg:命令行的视频格式转换程序。
ffplay:视频播放程序。(需要SDL支持)
ffserver:多媒体服务器
了解完组成结构后,你会发现,如果你在寻找一种视频格式转换的方式,那FFmpeg绝对是你的第一选择,libavcodec 则又是重 中之重。如果遇上API不会使用的情况,可以参考ffmpeg.c、ffplay.c、 ffserver.c、apiexample.c(解码)和output_example.c(编码)。
ffmpeg使用说明
ffmpeg库的接口都是c函数,其头文件也没有extern “C”的声明,所以在cpp文件里调用ffmpeg函数要注意了。一般来说,一个用C写成的库如果想被C/C++同时可以使用,那在头文件应该加上
123456 | #ifdef __cplusplusextern "C" {#endif#ifdef __cplusplus} // endof extern "C"#endif |
和ffmpeg库提供的符号名不一致。
可以这么解决:
123456 | extern "C"{#include <libavutil/avutil.h>#include <libavcodec/avcodec.h>#include <libavformat/avformat.h>} |
使用ffmpeg SDK解码流数据过程
以H264视频流为例,讲解解码流数据的步骤。准备变量
定义***Codec,***Codec *变量为解码器指针。定义***CodecContext,使用该变量可以将其定义为ffmpeg解码类的类成员。
定义***Frame,***Frame描述一个多媒体帧。解码后的数据将被放在其中。
定义***FormatContext变量,***FormatContext用于保存视频流的有效信息。
1234 | ***Codec *pCodec;***CodecContext * pCodecCtx;***Frame * pAvFrame;***FormatContext *pFormatCtx; |
初始化解码器
第一件事情就是初始化libavformat/libavcodec:ffmpeg注册复用器,编码器等的函数av_register_all()。
1 | av_register_all(); |
打开视频文件,取出包含在文件中的流信息
123 | // 打开视频文件if(av_open_input_file(&pFormatCtx, filename, NULL, 0, NULL)!=0) handle_error(); // 不能打开此文件 |
最后三个参数描述了文件格式,缓冲区大小(size)和格式参数;我们通过简单地指明NULL或0告诉 libavformat 去自动探测文件格式并且使用默认的缓冲区大小。
123 | // 取出流信息if(av_find_stream_info(pFormatCtx)<0) handle_error(); // 不能够找到流信息 |
这一步会用有效的信息把 ***FormatContext 的流域(streams field)填满。作为一个可调试的诊断,我们会将这些信息全盘输出到标准错误输出中,不过你在一个应用程序的产品中并不用这么做。
我们仅仅处理视频流,而不是音频流。为了让这件事情更容易理解,我们只简单使用我们发现的第一种视频流。
12345678910111213141516 | //遍历文件的各个流,找到第一个视频流,并记录该流的编码信息videoindex = -1;for(i=0; i<pFormatCtx->nb_streams; i++) { if(pFormatCtx->streams[i]->codec->codec_type==***MEDIA_TYPE_VIDEO) { videoindex=i; break; }}if(videoindex==-1){ printf("Didn't find a video stream.\n"); return;}pCodecCtx=pFormatCtx->streams[videoindex]->codec; |
寻找视频流的解码器
在库里面查找支持该格式的解码器123 | pCodec = avcodec_find_decoder(pCodecCtx->codec_id);if(pCodec == NULL) handle_error(); // 找不到解码器 |
打开解码器
12 | if(avcodec_open(pCodecCtx, pCodec)<0) handle_error(); |
给视频帧分配空间,以便存储解码后的图片数据
1 | pAvFrame = avcodec_alloc_frame(); |
进行解码
通过该api读入一帧1 | result = av_read_frame(pFormatCtx, packet); |
1 | ret = avcodec_decode_video2(pCodecCtx, pAvFrame, &got_picture, packet); |
将YUV420p颜色编码转换成BGR颜色编码
首先得到图片转换上下文img_convert_ctx,这里注意的是,opencv的RGB编码顺序为BGR,所以选用***_PIX_FMT_BGR24的编码方式。123456 | //根据编码信息设置渲染格式 if(img_convert_ctx == NULL){ img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, ***_PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL); } |
12345678 | ***Frame *pFrameRGB = NULL;uint8_t *out_bufferRGB = NULL;pFrameRGB = avcodec_alloc_frame();//给pFrameRGB帧加上分配的内存;int size = avpicture_get_size(***_PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height);out_bufferRGB = new uint8_t[size];avpicture_fill((***Picture *)pFrameRGB, out_bufferRGB, ***_PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height); |
1 | sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize); |
OpenCV Mat数据复制
cv::Mat对象中有data指针,指向内存中存放矩阵数据的一块内存 (uchar* data)。所以,要将ffmpeg解码之后得到的RGB色彩的帧数据复制给该指针,这样就实现了ffmpeg解码数据到opencv中Mat格式的转换,进而就可以对Mat对象进行相应的处理。
代码示例
ffmpegDecode.h文件
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 | #ifndef __FFMPEG_DECODE_H__#define __FFMPEG_DECODE_H__#include <opencv2/core/core.hpp>extern "C"{#include "libavcodec/avcodec.h"#include "libavformat/avformat.h"//图像转换结构需要引入的头文件#include "libswscale/swscale.h"};#pragma comment(lib, "avcodec.lib")#pragma comment(lib, "avformat.lib ")#pragma comment(lib, "avutil.lib ")#pragma comment(lib, "avdevice.lib ")#pragma comment(lib, "avfilter.lib ")#pragma comment(lib, "postproc.lib ")#pragma comment(lib, "swresample.lib")#pragma comment(lib, "swscale.lib ")class ffmpegDecode{public: ffmpegDecode(char * file = NULL); ~ffmpegDecode(); cv::Mat getDecodedFrame(); cv::Mat getLastFrame(); int readOneFrame(); int getFrameInterval();private: ***Frame *pAvFrame; ***FormatContext *pFormatCtx; ***CodecContext *pCodecCtx; ***Codec *pCodec; int i; int videoindex; char *filepath; int ret, got_picture; SwsContext *img_convert_ctx; int y_size; ***Packet *packet; cv::Mat *pCvMat; void init(); void openDecode(); void prepare(); void get(***CodecContext *pCodecCtx, SwsContext *img_convert_ctx,***Frame *pFrame);};#endif |
ffmpegDecode.cpp文件
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203 | #include "ffmpegDecode.h"ffmpegDecode :: ~ffmpegDecode(){ pCvMat->release(); //释放本次读取的帧内存 av_free_packet(packet); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx);}ffmpegDecode :: ffmpegDecode(char * file){ pAvFrame = NULL/**pFrameRGB = NULL*/; pFormatCtx = NULL; pCodecCtx = NULL; pCodec = NULL; pCvMat = new cv::Mat(); i=0; videoindex=0; ret = 0; got_picture = 0; img_convert_ctx = NULL; y_size = 0; packet = NULL; if (NULL == file) { filepath = "opencv.h264"; } else { filepath = file; } init(); openDecode(); prepare(); return;}void ffmpegDecode :: init(){ //ffmpeg注册复用器,编码器等的函数av_register_all()。 //该函数在所有基于ffmpeg的应用程序中几乎都是第一个被调用的。只有调用了该函数,才能使用复用器,编码器等。 //这里注册了所有的文件格式和编解码器的库,所以它们将被自动的使用在被打开的合适格式的文件上。注意你只需要调用 av_register_all()一次,因此我们在主函数main()中来调用它。如果你喜欢,也可以只注册特定的格式和编解码器,但是通常你没有必要这样做。 av_register_all(); //pFormatCtx = avformat_alloc_context(); //打开视频文件,通过参数filepath来获得文件名。这个函数读取文件的头部并且把信息保存到我们给的***FormatContext结构体中。 //最后2个参数用来指定特殊的文件格式,缓冲大小和格式参数,但如果把它们设置为空NULL或者0,libavformat将自动检测这些参数。 if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL)!=0) { printf("无法打开文件\n"); return; } //查找文件的流信息,avformat_open_input函数只是检测了文件的头部,接着要检查在文件中的流的信息 if(av_find_stream_info(pFormatCtx)<0) { printf("Couldn't find stream information.\n"); return; } return;}void ffmpegDecode :: openDecode(){ //遍历文件的各个流,找到第一个视频流,并记录该流的编码信息 videoindex = -1; for(i=0; i<pFormatCtx->nb_streams; i++) { if(pFormatCtx->streams[i]->codec->codec_type==***MEDIA_TYPE_VIDEO) { videoindex=i; break; } } if(videoindex==-1) { printf("Didn't find a video stream.\n"); return; } pCodecCtx=pFormatCtx->streams[videoindex]->codec; //在库里面查找支持该格式的解码器 pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL) { printf("Codec not found.\n"); return; } //打开解码器 if(avcodec_open2(pCodecCtx, pCodec,NULL) < 0) { printf("Could not open codec.\n"); return; }}void ffmpegDecode :: prepare(){ //分配一个帧指针,指向解码后的原始帧 pAvFrame=avcodec_alloc_frame(); y_size = pCodecCtx->width * pCodecCtx->height; //分配帧内存 packet=(***Packet *)av_malloc(sizeof(***Packet)); av_new_packet(packet, y_size); //输出一下信息----------------------------- printf("文件信息-----------------------------------------\n"); av_dump_format(pFormatCtx,0,filepath,0); //av_dump_format只是个调试函数,输出文件的音、视频流的基本信息了,帧率、分辨率、音频采样等等 printf("-------------------------------------------------\n");}int ffmpegDecode :: readOneFrame(){ int result = 0; result = av_read_frame(pFormatCtx, packet); return result;}cv::Mat ffmpegDecode :: getDecodedFrame(){ if(packet->stream_index==videoindex) { //解码一个帧 ret = avcodec_decode_video2(pCodecCtx, pAvFrame, &got_picture, packet); if(ret < 0) { printf("解码错误\n"); return cv::Mat(); } if(got_picture) { //根据编码信息设置渲染格式 if(img_convert_ctx == NULL){ img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, ***_PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL); } //----------------------opencv if (pCvMat->empty()) { pCvMat->create(cv::Size(pCodecCtx->width, pCodecCtx->height),CV_8UC3); } if(img_convert_ctx != NULL) { get(pCodecCtx, img_convert_ctx, pAvFrame); } } } av_free_packet(packet); return *pCvMat;}cv::Mat ffmpegDecode :: getLastFrame(){ ret = avcodec_decode_video2(pCodecCtx, pAvFrame, &got_picture, packet); if(got_picture) { //根据编码信息设置渲染格式 img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL); if(img_convert_ctx != NULL) { get(pCodecCtx, img_convert_ctx,pAvFrame); } } return *pCvMat;}void ffmpegDecode :: get(***CodecContext * pCodecCtx, SwsContext * img_convert_ctx, ***Frame * pFrame){ if (pCvMat->empty()) { pCvMat->create(cv::Size(pCodecCtx->width, pCodecCtx->height),CV_8UC3); } ***Frame *pFrameRGB = NULL; uint8_t *out_bufferRGB = NULL; pFrameRGB = avcodec_alloc_frame(); //给pFrameRGB帧加上分配的内存; int size = avpicture_get_size(***_PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height); out_bufferRGB = new uint8_t[size]; avpicture_fill((***Picture *)pFrameRGB, out_bufferRGB, ***_PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height); //YUV to RGB sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize); memcpy(pCvMat->data,out_bufferRGB,size); delete[] out_bufferRGB; av_free(pFrameRGB);} |
Github主页(http://jasonding1354.github.io/)
CSDN博客(http://blog.csdn.net/jasonding1354)
简书主页(http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles)
相关文章推荐
- linux程序设计——执行SQL语句(第八章)
- php面试题之四——Linux部分(高级部分)
- 搭建自己的 Docker 私有仓库服务
- Tomcat启动时卡在“INFO: Deploying web application directory ......”的解决方法
- Unix IPC进程间通信
- OpenGL ES 2.0 Shader相关介绍
- 【Hadoop】3、Hadoop安装之cloudera manager(1)
- Centos6.4下配置邮件服务器postfix3.0.1(一)
- 使用OpenCV滑动条写成的简单调色器,实时输出RGB值
- 给网站加第三方社交登录的
- Tomcat优化及压力测试实例 .
- Linux源文件夹结构呈现
- 虚拟化中当将windows或者linux克隆后怎么处理
- linux shell脚本攻略 学习笔记1 -- 第一章 小试牛刀
- Linux远程登陆以及免密码登陆
- openstack nova 基础知识——policy【转载】
- linux zip/unzip命令详解
- shuffle和排序
- linux核心技术免费学习视频
- SHOPPICA OPENCART 商城自适应主题模板 ABC-0002