对采集到得摄像头图像进行编码保存,发现得到的视频质量不好,而且速度不对。下面是关键代码。高手们看看,问:
1.编码器和AVPacket的pts设置对不对?
2.AVPacket的dts要设置吗?设为多少?
3.编码质量不好可不可以通过设置pStream->quality = m_nQuality调节?
下面是小弟做的:
首先,编码器类型是通过文件格式guess得到;
其次,下面是初始化AVStream编码器的函数:
AVStream *pStream = av_new_stream(pFormatContext, 0);
if( NULL == pStream )
return NULL;
AVCodecContext *pCodecContext = pStream->codec;
pCodecContext->codec_id = (CodecID)codec_id; //guess得到
pCodecContext->codec_type = CODEC_TYPE_VIDEO;
pCodecContext->bit_rate = (int)m_fBitRate; //固定设置为了1000000
pCodecContext->width = m_nWidth; //图像宽度:我这里是2048
pCodecContext->height = m_nHeight; //图像高度:我这里是1356
pCodecContext->time_base.den = 30; //这个不懂怎么设置,设为25或30以外的任何数值都
//会导致avcodec_open()调用失败,我就只好这么设置了
pCodecContext->time_base.num = 1; //以下设置都是参考的out_example.c
pCodecContext->gop_size = 12;
pCodecContext->pix_fmt = PIX_FMT_YUV420P;
if (pCodecContext->codec_id == CODEC_ID_MPEG2VIDEO)
pCodecContext->max_b_frames = 2;
if (pCodecContext->codec_id == CODEC_ID_MPEG1VIDEO)
pCodecContext->mb_decision=2;
if(!strcmp(pFormatContext->oformat->name, "mp4") || !strcmp(pFormatContext->oformat->name, "mov") ||
!strcmp(pFormatContext->oformat->name, "3gp"))
pCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
return pStream;
然后我进行了编码保存,其实也是参考out_example.c,只是速度老不对,自己改写了pts,dts实在不知道怎么填:
if (pFormatcontext->oformat->flags & AVFMT_RAWPICTURE) {
/* raw video case. The API will change slightly in the near
futur for that */
AVPacket pkt;
av_init_packet(&pkt);
pkt.flags |= PKT_FLAG_KEY;
pkt.stream_index= pVideoStream->index;
pkt.data= (uint8_t *)m_pYUVFrame;
pkt.size= sizeof(AVPicture);
ret = av_write_frame(pFormatcontext, &pkt);
}
else{
int out_size = avcodec_encode_video(pCodecContext, m_pOutBuf, m_nOutBufSize, m_pYUVFrame);
if (out_size > 0){
AVPacket pkt;
av_init_packet(&pkt);
//pkt.pts = av_rescale_q(pCodecContext->coded_frame->pts, pCodecContext->time_base,pVideoStream->time_base);//原来是这样的
pkt.pts = currTickCount - startTickCount;//我记录了每一帧来的时间和第一帧时间,将这个差值作为pts,
//不知道这样有什么问题吗?
if( pCodecContext->coded_frame->key_frame )
pkt.flags |= PKT_FLAG_KEY;
pkt.stream_index = pVideoStream->index;
pkt.data= m_pOutBuf;
pkt.size= out_size;
ret = av_write_frame(pFormatcontext, &pkt);
}else{
ret = 0;
}
}
------解决方案--------------------------------------------------------