最近在研究Windows下x264編碼h264,在網上找了一些,發現很多程式不全,或者在Linux平台下的程式,于是從網上找了一些代碼,修改了一下,适合在Windows下利用VS2012編譯運作。
首先從x264的官網下載下傳x264的源代碼,http://www.videolan.org/developers/x264.html,裡面有源代碼以及Windows下生成好的lib庫檔案、x264頭檔案以及一些必備的dll檔案。
然後配置VS2012的庫目錄路徑以及頭檔案的包含目錄路徑,然後再添加附加依賴項,如下圖:

x264編碼源程式如下:
/***********************************************************************
*作者:HJL
*編寫日期:2015.7.16
*效果:x264軟體編碼,将輸入的yuv視訊檔案編碼為h264視訊檔案
*程式中要設定2處:
*1.設定視訊的寬高
*2.設定待轉碼yuv視訊的路徑
************************************************************************/
#include <iostream>
#include <string>
#include "stdint.h"
//#include <time.h>
extern "C"
{
#include "x264.h"
#include "x264_config.h"
};
int main(int argc, char** argv)
{
///
///
//設定視訊的寬度、高度
int width = 480;
int height = 272;
///
int fps = 25;//設定幀率
size_t yuv_size = width * height * 3 / 2;
x264_t *encoder;
x264_picture_t pic_in, pic_out;
uint8_t *yuv_buffer;
x264_param_t param;
x264_param_default_preset(¶m, "veryfast", "zerolatency");
param.i_threads = 1;
param.i_width = width;
param.i_height = height;
param.i_fps_num = fps;//視訊資料幀率
param.i_fps_den = 1;
param.i_keyint_max = 25;
param.b_intra_refresh = 1;
param.b_annexb = 1;
x264_param_apply_profile(¶m, "baseline");
encoder = x264_encoder_open(¶m);
x264_picture_alloc(&pic_in, X264_CSP_I420, width, height);
yuv_buffer =(uint8_t*) malloc(yuv_size);
pic_in.img.plane[0] = yuv_buffer;
pic_in.img.plane[1] = pic_in.img.plane[0] + width * height;
pic_in.img.plane[2] = pic_in.img.plane[1] + width * height / 4;
int64_t i_pts = 0;
x264_nal_t *nals;
int nnal;
/
//讀取yuv視訊檔案,即待轉碼yuv檔案
FILE *inf=fopen("ds_480x272.yuv","rb");
//* 建立檔案,用于存儲編碼資料
FILE *outf=fopen("test.h264","ab");
if(NULL==inf)
{
return -1;
}
while (fread(yuv_buffer, 1, yuv_size,inf) > 0)
{
pic_in.i_pts = i_pts++;
x264_encoder_encode(encoder, &nals, &nnal, &pic_in, &pic_out);
x264_nal_t *nal;
for (nal = nals; nal < nals + nnal; nal++)
{
fwrite( nal->p_payload, 1, nal->i_payload,outf);//寫h264
}
}
x264_encoder_close(encoder);
fclose(inf);
fclose(outf);
free(yuv_buffer);
return 0;
}
</span>
整體VS2012的工程可以在這裡下載下傳。
最後效果如下:
原始yuv視訊:
編碼後的h264視訊如下:
yuv、h264視訊播放器可以在這裡下載下傳。
參考文章:http://www.cnblogs.com/fojian/archive/2012/09/01/2666627.html#2571019