利用x264lib编码h264流的源码(二)

2014-11-24 11:43:26 · 作者: · 浏览: 1
_AUTOVARIANCE*/;
param.rc.f_aq_strength = 0.3f;
param.i_log_level = X264_LOG_NONE;

h = x264_encoder_open( m);
if(h == NULL)
{
return false;
}

m_usWidth=usWidth;
m_usHeight=usHeight;
return true;
}

static int encode_nals(unsigned char *buf, x264_nal_t *nals, int nnal)
{
unsigned char *p = buf;
int i;

for(i = 0; i < nnal; i++)
{
int nsize = 0;
int s = x264_nal_encode(p, &nsize, 1, nals + i);
if(s < 0)
return -1;
p += s;
}

return p - buf;
}

bool x264enc::X264Encode(unsigned char* pInFrame,const int& nInLen,unsigned char* pOutFrame,int& nOutLen,bool& bKeyFrame)
{
x264_nal_t *nal;
x264_picture_t pic_out;
x264_picture_t pic;
int nnal = 0;
if(pInFrame)
{
pic.img.i_csp = X264_CSP_I420;
pic.img.i_plane = 3;
pic.img.plane[0] = pInFrame;
pic.img.plane[1] = pInFrame + m_usWidth*m_usHeight;
pic.img.plane[2] = pic.img.plane[1] + (m_usWidth*m_usHeight / 4);
pic.img.i_stride[0] = m_usWidth;
pic.img.i_stride[1] = m_usWidth / 2;
pic.img.i_stride[2] = m_usWidth / 2;
pic.i_type = X264_TYPE_AUTO;

if(x264_encoder_encode(h, &nal, &nnal, &pic, &pic_out) < 0)
{
return false;
}
}
else
{
if(x264_encoder_encode(h, &nal, &nnal, NULL, &pic_out) < 0)
{
return false;
}
}

if(nnal <= 0)
return false;

nOutLen = encode_nals(pOutFrame, nal, nnal);

if(nOutLen < 0)
{
return false;
}
if(pic_out.i_type == X264_TYPE_IDR)
{
bKeyFrame = true;
}
else
{
bKeyFrame = false;
}
return true;
}

void x264enc::ReleaseConnection()
{
if(h)
{
x264_encoder_close(h);
h = NULL;
}
delete this;
}

main.cpp:

[cpp]
#include "stdafx.h"
#include
#include "x264enc.h"

int main(int argc, char* argv[])
{
if (argc != 5)
{
printf("please input: Enc_Demo.exe filename1[input] Width Height filename2[output]\n");
}


//params set
unsigned short usWidth = atoi(argv[2]);
unsigned short usHeight = atoi(argv[3]);

//create X264 instance
x264enc* pX264enc = new x264enc;

if(!pX264enc || !pX264enc->InitX264Encoder(usWidth, usHeight, 100, 5, 26))
{
pX264enc->ReleaseConnection();
delete pX264enc;
return -1;
}

unsigned char *p_In_Frame = new unsigned char[usWidth * usHeight * 3/2];
unsigned char *p_Out_Frame = new unsigned char[usWidth * usHeight * 3/2];
FILE* ifp = fopen(argv[1],"rb");
FILE* ofp = fopen(argv[4],"wb");

bool b_continue = true;
int nReadUnit = usWidth * usHeight * 3/2;
while (b_continue || !feof(ifp))
{
int n_OutFrame_Size = 0;
bool bKeyFrame = false;
int nCount = fread(p_In_Frame, 1, nReadUnit, ifp);
if(nCount != nReadUnit)
{
b_continue = false;
break;
}

unsigned char *pSrc = p_In_Frame;
if(pX264enc->X264Encode(pSrc, nCount, p_Out_Frame, n_OutFrame_Size,bKeyFrame))
{
fwrite(p_Out_Frame, n_OutFrame_Size, 1, ofp);
}
}

do
{
int n_OutFrame_Size = 0;
bool b_KeyFrame = false;
if(pX264enc->X264Encode(NULL, 0, p