h.264 视频解码的一点小经验(ffmpeg)

最近做视频文件264解码,由于对这个领域不是很熟悉,感觉困难重重。不过经过不懈的努力,已经取得一些进展,心里感觉特别庆幸。 刚开始做这个的时候,由于不熟悉,就在网上搜寻资料,网络上的资料虽然多,但是却很杂乱,因此一开始走了不少弯路,现在把我的一点小小心得写出来,后来的兄弟们可以参考一下,没准能够少走些弯路。当然啦,我在视频处理方面仍然是个非常菜的菜鸟,如果是高手路过,看到我这所谓的“心得”,也请不要见笑,看到不对的地方请批评指正,呵呵。

刚开始做的时候,先是在网络上查找资料,我觉得有一篇文章非常的有用,因为当时我最需要了解的就是世界上现存的各种编解码器,每种都有什么特性,比如说解码速度是否能够满足实时播放的需求、对h.264标准的支持程度等等。这篇文章就是《H.264开源解码器评测》,这篇文章详细的评测了当今流行的几种h.264解码器,包括JM Decoder,T264 Decoder,X264 Decoder,ffmpeg libavcodec和Intel的IPP库,经过作者的评测,发现速度最快的就是intel IPP了,但是intel IPP属于商品化软件,而其他的各种解码器都属于开源项目,所以最适合选择的就是解码速度第二的ffmpeg了,而且其速度完全可以满足实时播放的要求;

选择好了解码器,第一步算是完成了,第二步就是研究ffmpeg的用法了。经过摸索,我的选择是:到中华视频网下在ffmpeg SDK 2.0,这恐怕是目前最适合在VC++6下使用的基于ffmpeg的SDK了,其易用性比较好。

第三步就是编写播放器外壳了,外壳代码采用VC++6编写,我会在文张末尾给出外壳的所有代码;注意:外科代码获取的lpdata是windows内存位图,具有dword对齐的特性,另外,解码出的图像是倒立的,因此我专门写了一个把图像倒转的函数,运行速度还是挺快的,完全不妨碍实时播放;

上一阶段的工作完成得还算满意,下一阶段的工作就是h.264 的 RTP payload协议了。

附录:

h.264播放的外壳代码-------------------------------------------------------------------------------------------------

// Decode264.cpp : Defines the initialization routines for the DLL.

#include "stdafx.h"
#include "Decode264.h"

//以下代码为自己添加
#include <stdlib.h>
#include <time.h>
#include "avformat.h"
#include "avcodec.h"
#include <windows.h>

//定义目标格式
#define DEST_FORMAT PIX_FMT_BGR24
//PIX_FMT_YUV420P

//定义全局变量
AVFormatContext *pFormatCtx; //
int i, videoStream;
AVCodecContext *pCodecCtx;
AVCodec *pCodec; //编解码器
AVFrame *pFrame; //帧
AVFrame *pFrameYUV; //YUV帧

clock_t t;
double fps;
int y_size, i_frame=0;
int numBytes;
uint8_t *buffer;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//
// Note!
//
// If this DLL is dynamically linked against the MFC
// DLLs, any functions exported from this DLL which
// call into MFC must have the AFX_MANAGE_STATE macro
// added at the very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//

/
// CDecode264App

BEGIN_MESSAGE_MAP(CDecode264App, CWinApp)
//{{AFX_MSG_MAP(CDecode264App)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CDecode264App construction

CDecode264App::CDecode264App()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}

/
// The one and only CDecode264App object

CDecode264App theApp;

//以下代码为自己添加/

//把图像倒立过来;
long UpendBmp(unsigned char *lpdata,long width ,long height)
{

long lBPL;//每行的字节数,因为要考虑dword对齐
long x,y,idx_src,idx_dest;
unsigned char *tmpdata;

if (0==((width*3)%4)) //nWidth * 3 是存储每行像素需要的字节数,如果是4的整数倍。
lBPL = (width*3); //那么返回 nWidth * 3 ,就是每行的字节数
else //如果不是4的整数倍,那么就一定要加上一个数,达到4的整数倍,才是每行的字节数。
lBPL = (width*3+(4-((width*3)%4)));

tmpdata= new unsigned char[lBPL * height];

x =0;
for (y=0 ; y<height ; y++)
{
idx_src =(height-1-y)*lBPL;//idx_src =(height-1-y)*lBPL+x*3;优化前
idx_dest=y*lBPL;//idx_dest=y*lBPL+x*3;优化前
memcpy(&tmpdata[idx_dest],&lpdata[idx_src],lBPL);//复制一行
}

memcpy(lpdata,tmpdata,lBPL * height);
delete[] tmpdata;

return 0;
}

//创建一个bmp文件。用于调试
static int av_create_bmp(char* filename,uint8_t *pRGBBuffer,
int width,int height,int bpp)
{
BITMAPFILEHEADER bmpheader;
BITMAPINFO bmpinfo;
FILE *fp;

fp = fopen(filename,"wb");
if(!fp)return -1;

bmpheader.bfType = (''M''<<8)|''B'';
bmpheader.bfReserved1 = 0;
bmpheader.bfReserved2 = 0;
bmpheader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmpheader.bfSize = bmpheader.bfOffBits + width*height*bpp/8;

bmpinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpinfo.bmiHeader.biWidth = width;
bmpinfo.bmiHeader.biHeight = height;
bmpinfo.bmiHeader.biPlanes = 1;
bmpinfo.bmiHeader.biBitCount = bpp;
bmpinfo.bmiHeader.biCompression = BI_RGB;
bmpinfo.bmiHeader.biSizeImage = 0;
bmpinfo.bmiHeader.biXPelsPerMeter = 100;
bmpinfo.bmiHeader.biYPelsPerMeter = 100;
bmpinfo.bmiHeader.biClrUsed = 0;
bmpinfo.bmiHeader.biClrImportant = 0;

fwrite(&bmpheader,sizeof(BITMAPFILEHEADER),1,fp);
fwrite(&bmpinfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,fp);
fwrite(pRGBBuffer,width*height*bpp/8,1,fp);
fclose(fp);

return 0;
}

//获取下一帧
static bool GetNextFrame(AVFormatContext *pFormatCtx,
AVCodecContext *pCodecCtx,
int videoStream,
AVFrame *pFrame)
{
static AVPacket packet; //AV包。静态变量。
static int bytesRemaining=0; //字节剩余。静态变量。
static uint8_t *rawData; //原始数据字节数。静态变量。
static bool fFirstTime=true; //标志,第一次;。静态变量。
int bytesDecoded; //解码后获得的字节;
int frameFinished; //帧解码完毕标志;

// First time we''re called, set packet.data to NULL to indicate it
// doesn''t have to be freed 当第一次被调用的时候,把packet.data设置为NULL,以表示
//它没有必要被释放;
if (fFirstTime){
fFirstTime = false;
packet.data = NULL;
}

//解码那些包,直到我们解码出一个完整的帧;
// Decode packets until we have decoded a complete frame
while (true)
{
//在当前包上工作,直到我们解码出所有的。
//Work on the current packet until we have decoded all of it
while (bytesRemaining > 0)
{
// Decode the next chunk of data 解码出下一个数据块
bytesDecoded = avcodec_decode_video(pCodecCtx, pFrame,
&frameFinished, rawData, bytesRemaining);

// Was there an error?
if (bytesDecoded < 0){
fprintf(stderr, "Error while decoding frame\\n");
return false;
}

bytesRemaining -= bytesDecoded;
rawData += bytesDecoded;

// Did we finish the current frame? Then we can return
if (frameFinished) //如果我们完成了当前帧的解码,就可以返回了
return true;
}

//读取下一个包,跳过所有的不是属于这个流的包;
// Read the next packet, skipping all packets that aren''t for this
// stream
do{
// Free old packet 释放旧包
if(packet.data != NULL)
av_free_packet(&packet);

// Read new packet 读取新包
if(av_read_frame(pFormatCtx, &packet) < 0)
goto loop_exit;
} while(packet.stream_index != videoStream); //当不是要找的视频流的时候,继续循环,就是重新读了;
//直到找到要找的视频流,退出循环;

bytesRemaining = packet.size; //纪录包的字节数;
rawData = packet.data; //
}

loop_exit:

// Decode the rest of the last frame
bytesDecoded = avcodec_decode_video(pCodecCtx, pFrame, &frameFinished,
rawData, bytesRemaining);

// Free last packet
if(packet.data != NULL)
av_free_packet(&packet);

return frameFinished != 0;
}

//对外的API接口。打开264文件,并且获取必要的信息,比如宽度高度帧数等等
long __stdcall open264file(char *filename,long *out_width ,
long *out_height,long *out_framenum,
long *out_bufsize)
{


// Register all formats and codecs 注册所有的格式和编解码器
av_regi[FS:PAGE]ster_all();

// Open video file//打开视频文件
if (av_open_input_file(&pFormatCtx, filename, NULL, 0, NULL) != 0)
return -1; // Couldn''t open file如果不能打开,那么返回-1

// Retrieve stream information 取流信息
if (av_find_stream_info(pFormatCtx) < 0)
return -1; // Couldn''t find stream information

// Dump information about file onto standard error
dump_format(pFormatCtx, 0, filename, false);

t = clock();

// Find the first video stream 寻找第一个视频流
videoStream = -1;
for (i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type == CODEC_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;

// Find the decoder for the video stream 获取解码器
pCodec = avcodec_find_decoder(pCodecCtx->codec_id);

if (pCodec == NULL)
return -1; // Codec not found解码器没有找到;

//告知解码器,我们能处理被删节的位流
// 也就是说,帧的分界处的位流可以落到包的中间;
// Inform the codec that we can handle truncated bitstreams -- i.e.,
// bitstreams where frame boundaries can fall in the middle of packets
if ( pCodec->capabilities & CODEC_CAP_TRUNCATED )
pCodecCtx->flags|=CODEC_FLAG_TRUNCATED;

// Open codec //打开解码器
if ( avcodec_open(pCodecCtx, pCodec) < 0 )
return -1; // Could not open codec 不能打开解码器,返回-1;

// Allocate video frame 分配视频帧
pFrame = avcodec_alloc_frame();

// Allocate an AVFrame structure 分配一个AVFrame结构
pFrameYUV=avcodec_alloc_frame(); //解码后的帧
if(pFrameYUV == NULL)
return -1;

//决定需要多大的缓冲空间,并且分配空间;
// Determine required buffer size and allocate buffer
numBytes=avpicture_get_size(DEST_FORMAT, pCodecCtx->width,
pCodecCtx->height);
buffer = (uint8_t*)malloc(numBytes);

//向外界输出宽高、帧数;
*out_width = pCodecCtx->width;
*out_height = pCodecCtx->height;
*out_framenum = pCodecCtx->frame_number;
*out_bufsize = numBytes;

// Assign appropriate parts of buffer to image planes in pFrameRGB
//把缓冲区中合适的部分指派到pFrameRGB中的图像面板
avpicture_fill((AVPicture *)pFrameYUV, buffer, DEST_FORMAT,
pCodecCtx->width, pCodecCtx->height);

return 0;
}

//对外的API接口。关闭264文件,释放相关资源
long __stdcall close264file()
{
//calculate decode rate 计算解码速率
t = clock() - t;
fps = (double)(t) / CLOCKS_PER_SEC;
fps = i_frame / fps;
printf("\\n==>Decode rate %.4f fps!\\n", fps);

// Free the YUV image 释放yuv图像
free(buffer);
av_free(pFrameYUV);

// Free the YUV frame 释放yuv帧
av_free(pFrame);
// Close the codec 关闭解码器
avcodec_close(pCodecCtx);
// Close the video file 关闭视频文件
av_close_input_file(pFormatCtx);

return 0;
}

//对外的API接口。获取一帧解码后的数据
long __stdcall GetNextFrame(unsigned char *lpdata)
{

// Read frames 读取个个帧
if (GetNextFrame(pFormatCtx, pCodecCtx, videoStream, pFrame))
{
img_convert((AVPicture *)pFrameYUV, DEST_FORMAT, (AVPicture*)pFrame,
pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);


//调试用,向C盘写入一个bmp文件;
//av_create_bmp("c:\\\\1.bmp",(unsigned char *)pFrameYUV->data[0],pCodecCtx->width,pCodecCtx->height,24);

i_frame++;
y_size = pCodecCtx->width * pCodecCtx->height;

//写入文件
/*fwrite(pFrameYUV->data[0], 1, y_size, fp);
fwrite(pFrameYUV->data[1], 1, (y_size/4), fp);
fwrite(pFrameYUV->data[2], 1, (y_size/4), fp);*/
memcpy(lpdata,pFrameYUV->data[0],y_size*3);
UpendBmp(lpdata,pCodecCtx->width,pCodecCtx->height);
return 0;
}
else
{return -1;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/254945.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HALCON示例程序novelty_detection_dyn_threshold.hdev纱网缺陷检测

HALCON示例程序novelty_detection_dyn_threshold.hdev纱网缺陷检测 示例程序源码&#xff08;加注释&#xff09; 关于显示类函数解释 dev_update_window (‘off’) read_image (Image, ‘plastic_mesh/plastic_mesh_01’) dev_close_window () get_image_size (Image, Width…

配置云服务器 FTP 服务

自己配置的环境: OS: 阿里云 CentOS 6.5 >>Begin: 1. 登录到阿里云服务器(如何登录阿里云服务器), 在root权限下, 通过如下命令安装 vsftp [rootVM_250_202_tlinux ~]# yum install vsftpd 2. 在启动vsftpd服务之前&#xff0c;需要登录云服务器修改配置文件&#xff0c;…

【跃迁之路】【428天】程序员高效学习方法论探索系列(实验阶段185-2018.04.09)...

(跃迁之路)专栏 实验说明 从2017.10.6起&#xff0c;开启这个系列&#xff0c;目标只有一个&#xff1a;探索新的学习方法&#xff0c;实现跃迁式成长实验期2年&#xff08;2017.10.06 - 2019.10.06&#xff09;我将以自己为实验对象。我将开源我的学习方法&#xff0c;方法不断…

opencv中的一些陷阱 坑死我了~~~~(_)~~~~

1.这几天被opencv给坑的够惨&#xff0c;好好的程序&#xff0c;先是因为imread&#xff08;&#xff09;不能读文件&#xff0c;整了很久没整出来&#xff0c;然后改了下path路径&#xff0c;没想到后面彻底奔溃了&#xff0c;&#xff0c;&#xff0c;&#xff0c;前后大概2天…

一篇需要膜拜的文篇--Javascript异步编程模型进化(转)

要我能用得这么熟&#xff0c; 那前端出师了哈。 http://foio.github.io/javascript-asyn-pattern/ 改天一个一个亲测一下。 Javascript语言是单线程的&#xff0c;没有复杂的同步互斥&#xff1b;但是&#xff0c;这并没有限制它的使用范围&#xff1b;相反&#xff0c;借助于…

很强大的FFMPEG API Documentation

http://wiki.aasimon.org/doku.php?idffmpeg:ffmpeg 点击打开链接

HALCON示例程序obj_diff.hdev算子obj_diff 的使用

HALCON示例程序obj_diff.hdev算子obj_diff 的使用 示例程序源码&#xff08;加注释&#xff09; 关于显示类函数解释 read_image (Image, ‘particle’)二值化 threshold (Image, Region, 57, 255)分割连通域 connection (Region, ConnectedRegions) dev_close_window () get…

JS函数方法Call Apply Bind运用

JS 函数非继承的call和apply方法 同&#xff1a;call & apply 主要是用于扩展this指向&#xff0c;降低this作用域与函数之间的耦合度&#xff1b; 区别&#xff1a;传参差异 function.call(this/object,params1,params2,...) 第一个参数为作用域指向参数&#xff0c;后边参…

IplImage, CvMat, Mat 的关系和相互转换 再次理解 /(ㄒoㄒ)/~~

opencv中常见的与图像操作有关的数据容器有Mat&#xff0c;cvMat和IplImage&#xff0c;这三种类型都可以代表和显示图像&#xff0c;但是&#xff0c;Mat类型侧重于计算&#xff0c;数学性较高&#xff0c;openCV对Mat类型的计算也进行了优化。而CvMat和IplImage类型更侧重于“…

HALCON示例程序optical_flow.hdev如何使用optical_flow_mg计算图像序列中的光流以及如何分割光流。

HALCON示例程序optical_flow.hdev如何使用optical_flow_mg计算图像序列中的光流以及如何分割光流。 示例程序源码&#xff08;加注释&#xff09; 关于显示类函数解释 dev_update_off () dev_close_window () read_image (Image1, ‘xing/xing000’) dev_open_window_fit_ima…

数字信号处理原理

关于傅里叶变换的解释&#xff0c;在下面的链接&#xff1a;http://blog.jobbole.com/70549/ 。讲的挺详细的&#xff1a; 注意点&#xff1a; 1、信号处理基于这么一个概念&#xff0c;待处理的信号&#xff08;&#xff1f;&#xff09;都可以分解为正弦波&#xff0c;不同…

webpack的一些常用配置 (转)

webpack 的配置文件就是 Node 的一个模块&#xff0c;它导出的将是一个对象 module.exports {entry: ./entry,output: {path: path.resolve(__dirname, dist),filename: bundle.js} }如果直接使用 webpack 来执行编译&#xff0c;webpack 默认读取的是当前目录下的 webpack.co…

CvMat,Mat和IplImage之间的转化和拷贝

1、CvMat之间的复制 //注意&#xff1a;深拷贝 - 单独分配空间&#xff0c;两者相互独立 CvMat* a; CvMat* b cvCloneMat(a); //copy a to b 2、Mat之间的复制 //注意&#xff1a;浅拷贝 - 不复制数据只创建矩阵头&#xff0c;数据共享&#xff08;更改a,b,c的任意一…

HALCON示例程序particle.hdev测量小圆部分

HALCON示例程序particle.hdev测量小圆部分 示例程序源码&#xff08;加注释&#xff09; 关于显示类函数解释 dev_update_off () dev_close_window () dev_open_window (0, 0, 512, 512, ‘black’, WindowID) set_display_font (WindowID, 14, ‘mono’, ‘true’, ‘false’…

Java List 分页

//分页&#xff0c;根据country或者site分br/>Overridepublic List<Integer> getSitesPage(Integer parentLevel, Integer currentPage) {List<Integer> subFrames getSites(parentLevel) ;int currentNum ( currentPage - 1 ) * CardViewUtil.PREPAGE_NUM ;D…

跟多导出数据库的方法

链接&#xff1a;http://www.2cto.com/database/201207/139330.html转载于:https://www.cnblogs.com/nycj/p/5661151.html

rtp协议详解/rtcp协议详解

、简介 目前&#xff0c;在IP网络中实现实时语音、视频通信和应用已经成为网络应用的一个主流技术和发展方向&#xff0c;本文详细介绍IP协议族中用于实时语音、视频数据传输的标准协议RTP&#xff08; Real-time Transport Protocol&#xff09;和RTCP&#xff08;RTP Control…

MVC开发中的常见错误-04-“System.NullReferenceException”类型的异常在 BBFJ.OA.WebApp.dll 中发生,但未在用户代码中进行处理...

未将对象引用设置到对象实例,又名空指针异常,伴随程序员开发的一生. 查看详细信息得知: SetUserRoleInfo() 首先想到的是 IBLL.IRoleInfoService RoleInfoService { set; get; }应该是config文件中反射出现了问题 <?xml version"1.0" encoding"utf-8"…

HALCON示例程序pcb_inspection.hdev检测pcb印刷缺陷

HALCON示例程序pcb_inspection.hdev检测pcb印刷缺陷 示例程序源码&#xff08;加注释&#xff09; 关于显示类函数解释 read_image (Image, ‘pcb’) dev_close_window () get_image_size (Image, Width, Height) dev_open_window (0, 0, Width, Height, ‘black’, WindowHa…

profibus GSD文件详解

profibus GSD文件详解 2015-6-19 通过PROFIBUS DP用功能块在主、从站之间实现双向数据传送&#xff1a;在主站PLC可以通过调用SFC14“DPRD_DAT”和SFC15“DPWR_DAT”来完成和从站的数据交换&#xff0c;而对于从站来说可以调用FC1“DP_SEND”和FC2“DP_RECV”完成数据的交换。 …