前段时间在Visual Studio里做过一次类似的Demo。现在尝试在Qt下使用X264对视频文件进行压缩。
首先编译X264库,在网上搜索后,发现X264库在Windows下的编译,针对VS和Qt很大部分是相同的。VS里用到的lib文件,是在能用于Qt的那些库文件基础上再继续编译生成的。所以,我此处就跳过编译的步骤了,使用上次在VS里使用的库文件。这些用到的文件列表如下:
其中benchmark.y4m是我们用以进行压缩的源视频文件。
将以上文件拷贝黏贴到当前工程目录下,并将3个头文件包含到工程中的头文件夹下。在pro文件里进行如下设置:
main.cpp
#include <iostream> #include <string> #include "stdint.h" extern "C" { #include "x264.h" #include "x264_config.h" #include "y4m.h" } #include <QDebug> int main() { int iResult=0; x264_t *pX264Handle=NULL; x264_param_t *pX264Param=new x264_param_t; // _assert(pX264Param); x264_param_default_preset(pX264Param, "veryfast", "zerolatency"); pX264Param->i_threads=X264_SYNC_LOOKAHEAD_AUTO; pX264Param->i_width=352; pX264Param->i_height=288; pX264Param->i_frame_total=0; pX264Param->i_keyint_max=10; pX264Param->i_bframe=5; pX264Param->b_open_gop=0; pX264Param->i_bframe_pyramid=0; pX264Param->i_bframe_adaptive=X264_B_ADAPT_TRELLIS; pX264Param->i_log_level=X264_LOG_DEBUG; pX264Param->rc.i_bitrate=1024*10; pX264Param->i_fps_den=1; pX264Param->i_fps_num=10; pX264Param->i_timebase_den=pX264Param->i_fps_num; pX264Param->i_timebase_num=pX264Param->i_fps_den; x264_param_apply_profile(pX264Param,x264_profile_names[0]); int iNal=0; x264_nal_t *pNals=NULL; x264_picture_t *pPicIn=new x264_picture_t; x264_picture_t *pPicOut=new x264_picture_t; x264_picture_init(pPicOut); x264_picture_alloc(pPicIn, X264_CSP_I420, pX264Param->i_width, pX264Param->i_height); pPicIn->img.i_csp=X264_CSP_I420; pPicIn->img.i_plane=3; pX264Handle=x264_encoder_open(pX264Param); // _ASSERT(pX264Handle); FILE *pFile=fopen("test.264","wb"); // _ASSERT(pFile); y4m_input_t *y4m_hnd=(y4m_input_t*)malloc(sizeof(y4m_input_t)); iResult=open_file_y4m("D:/Work/Test/build-TestX264_Qt-Desktop_Qt_5_3_0_MinGW_32bit-Debug/debug/benchmark.y4m", (hnd_t**)&y4m_hnd, pX264Param); if(iResult<0) { qDebug()<<"Failed to open file!"; return 0; } int nFrames=::get_frame_total_y4m((hnd_t*)y4m_hnd); for(int i=0;i<nFrames;i++) { read_frame_y4m(pPicIn,(hnd_t*)y4m_hnd,i); if(i==0) pPicIn->i_pts=i; else pPicIn->i_pts=i-1; int frame_size=x264_encoder_encode(pX264Handle, &pNals, &iNal, pPicIn, pPicOut); if(frame_size>0) { for(int i=0;i<iNal;++i) { fwrite(pNals[i].p_payload, 1, pNals[i].i_payload, pFile); } } } x264_picture_clean(pPicIn); x264_encoder_close(pX264Handle); pX264Handle=NULL; delete pPicIn; pPicIn=NULL; delete pPicOut; pPicOut=NULL; delete pX264Param; pX264Param=NULL; return 0; }
编译、运行,debug窗口会出现很多编译过程中产生的信息,如下图:
最后到编译路径的根目录下,可以发现test.264文件,大小是840K,源视频文件是44M,压缩效率是很理想的。