[C++] 纯文本查看 复制代码 int CodecH264::encode(char* data, int length, char* encBuf, int &encodedLength)
{
//only process one frame
if (m_pCodecCtxEnc == NULL)
{
iniEncode(m_nEncodeWidth,m_nEncodeHeight);
}
int nBufLen = 0;
static int i = 0;
int got_packet=0;
// av_init_packet(&packetEnc); 这种方式也不行, 所以主动new一个buf, 也不行。。。
// packetEnc.data = NULL;
// packetEnc.size = 0;
//主动new的buf
decodebuf = new unsigned char[VIDEO_DECODE_BUFFER_SIZE];
av_init_packet( &packetEnc );
packetEnc.data = decodebuf;
packetEnc.size = VIDEO_DECODE_BUFFER_SIZE;
//PIX_FMT_RGB24 PIX_FMT_YUYV422
//将数据保存到AVFrame中, data中是YUV数
int nRet = avpicture_fill((AVPicture*)m_pFrameEnc, (unsigned char *)data, PIX_FMT_YUV420P, m_nEncodeWidth, m_nEncodeHeight);
if ( nRet )
{
if( 0 == avcodec_encode_video2(m_pCodecCtxEnc,&packetEnc,m_pFrameEnc,&got_packet) )
{
encodedLength = packetEnc.size;
memcpy(encBuf, packetEnc.data, encodedLength);
}
m_pFrameEnc->pts = i++;
}
av_free_packet( &packetEnc );
return 0;
}
void CodecH264::iniEncode(int width,int height)
{
int nret = -1;
if (m_pCodecCtxEnc == NULL)
{
AVCodec *pCodec = avcodec_find_decoder(AV_CODEC_ID_H264);
m_pCodecCtxEnc = avcodec_alloc_context3(pCodec);
// put sample parameters
m_pCodecCtxEnc->bit_rate = 400000;
m_pCodecCtxEnc->width = width;//pCodecCtxDec->width;
m_pCodecCtxEnc->height = height;//pCodecCtxDec->height;
m_pCodecCtxEnc->time_base.num = 1;
m_pCodecCtxEnc->time_base.den = 25;
m_pCodecCtxEnc->gop_size = 10;
m_pCodecCtxEnc->max_b_frames = 1;
m_pCodecCtxEnc->pix_fmt = AV_PIX_FMT_YUV420P;
av_opt_set(m_pCodecCtxEnc->priv_data, "preset", "slow", 0);
if (avcodec_open2(m_pCodecCtxEnc, pCodec,NULL) < 0)
{
resetEnCode();
}
m_pFrameEnc = avcodec_alloc_frame();
if(!m_pFrameEnc)
{
resetEnCode();
}
m_pFrameEnc->format = m_pCodecCtxEnc->pix_fmt;
m_pFrameEnc->width = m_pCodecCtxEnc->width;
m_pFrameEnc->height = m_pCodecCtxEnc->height;
av_image_alloc(m_pFrameEnc->data, m_pFrameEnc->linesize, m_pCodecCtxEnc->width,
m_pCodecCtxEnc->height, m_pCodecCtxEnc->pix_fmt, 32);
}
}
代码如上, iniEncode是OK的, 在运行到avcodec_encode_video2时出现崩溃, 崩溃现象如图所示, 请大神指教, 谢谢
|