我编写了一段 C++ 代码,可以捕获网络摄像头视频帧,对其进行解码,将它们转换为 YUV420P,对其进行编码,然后将它们写入文件。如果我使用 mpeg2 编解码器并写入 .mpg 文件,则一切正常。但是,如果我使用 flv,那么产生的输出只是一个绿屏。我不确定是否需要为编码 flv 视频设置不同的编码器设置?这是我的代码(相关部分):
编码器设置:
c->codec_id = codec_id;
c->bit_rate = 400000;
// Resolution must be a multiple of two.
c->width = 352;
c->height = 288;
c->time_base.den = STREAM_FRAME_RATE;
c->time_base.num = 1;
//emit one intra frame every twelve frames at most
c->gop_size = 12;
c->pix_fmt = STREAM_PIX_FMT;
写框架:
int ret;
uint8_t *buffer = NULL;
static struct SwsContext *sws_ctx;
//Setup the codec context, and set its width and height to be equal to the input video width and height
AVCodecContext *c = st->codec;
c->width = pCodecCtx->width;
c->height = pCodecCtx->height;
av_init_packet(&packet);
frameYUV = avcodec_alloc_frame();
//Determine how big the buffer will need to be to store the captured frame
numBytes = avpicture_get_size(STREAM_PIX_FMT,pCodecCtx->width,pCodecCtx->height);
//Allocate the needed buffer size
buffer = new uint8_t[numBytes];
sws_ctx = sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,
pCodecCtx->width,pCodecCtx->height,
STREAM_PIX_FMT,SWS_BILINEAR,NULL,NULL,NULL);
//Fill the output frame
avpicture_fill((AVPicture *)frameYUV,buffer,STREAM_PIX_FMT,pCodecCtx->width,pCodecCtx->height);
//Read a video frame in
av_read_frame(pFormatCtx,&packet);
//Decode the contents of packet into pFrame
avcodec_decode_video2(pCodecCtx,pFrame,&frameFinished,&packet);
//Scale pFrame into frameYUV, and convert to PIXFMTYUV420P
sws_scale
(
sws_ctx,
(uint8_t const * const *)pFrame->data,
pFrame->linesize,
0,
pCodecCtx->height,
frameYUV->data,
frameYUV->linesize
);
av_init_packet(&samsPacket);
//Encode frameYUV
avcodec_encode_video2(c, &samsPacket, frameYUV, &gotSamsPacket);
AVPacket pkt = { 0 };
int got_packet;
av_init_packet(&pkt);
// encode the image
ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
if (ret < 0){
debugLogStreamSave->debug("Error encoding video frame");
exit(1);
}
if (!ret && got_packet && pkt.size){
pkt.stream_index = st->index;
// Write the compressed frame to our output
ret = av_interleaved_write_frame(oc, &pkt);