ubi*_*bik 5 c c++ ffmpeg video-encoding libavcodec
我通过v4l从相机抓取视频帧,我需要用mpeg4格式对它们进行转码,然后通过RTP连续流式传输.
一切都"有效",但重新编码时我没有:输入流产生15fps,输出为25fps,每个输入帧都在一个视频对象序列中转换(我通过简单的检查验证了这一点)在输出比特流上).我猜接收器正在正确解析mpeg4比特流,但RTP分组化在某种程度上是错误的.我应该如何在一个或多个AVPacket中拆分编码比特流?也许我错过了明显的,我只需要寻找B/P帧标记,但我想我没有正确使用编码API.
以下是我的代码的摘录,它基于可用的ffmpeg示例:
// input frame
AVFrame *picture;
// input frame color-space converted
AVFrame *planar;
// input format context, video4linux2
AVFormatContext *iFmtCtx;
// output codec context, mpeg4
AVCodecContext *oCtx;
// [ init everything ]
// ...
oCtx->time_base.num = 1;
oCtx->time_base.den = 25;
oCtx->gop_size = 10;
oCtx->max_b_frames = 1;
oCtx->bit_rate = 384000;
oCtx->pix_fmt = PIX_FMT_YUV420P;
for(;;)
{
// read frame
rdRes = av_read_frame( iFmtCtx, &pkt );
if ( rdRes >= 0 && pkt.size > 0 )
{
// decode it
iCdcCtx->reordered_opaque = pkt.pts;
int decodeRes = avcodec_decode_video2( iCdcCtx, picture, &gotPicture, &pkt );
if ( decodeRes >= 0 && gotPicture )
{
// scale / convert color space
avpicture_fill((AVPicture *)planar, planarBuf.get(), oCtx->pix_fmt, oCtx->width, oCtx->height);
sws_scale(sws, picture->data, picture->linesize, 0, iCdcCtx->height, planar->data, planar->linesize);
// encode
ByteArray encBuf( 65536 );
int encSize = avcodec_encode_video( oCtx, encBuf.get(), encBuf.size(), planar );
// this happens every GOP end
while( encSize == 0 )
encSize = avcodec_encode_video( oCtx, encBuf.get(), encBuf.size(), 0 );
// send the transcoded bitstream with the result PTS
if ( encSize > 0 )
enqueueFrame( oCtx->coded_frame->pts, encBuf.get(), encSize );
}
}
}
Run Code Online (Sandbox Code Playgroud)
最简单的解决方案是使用两个线程。第一个线程将执行您问题中概述的所有操作(解码、缩放/颜色空间转换、编码)。部分转码的帧将被写入与第二个线程共享的中间队列。在这种特殊情况下(从较低比特率转换为较高比特率),该队列的最大长度为 1 帧。第二个线程将从输入队列中读取循环帧,如下所示:
void FpsConverter::ThreadProc()
{
timeBeginPeriod(1);
DWORD start_time = timeGetTime();
int frame_counter = 0;
while(!shouldFinish()) {
Frame *frame = NULL;
DWORD time_begin = timeGetTime();
ReadInputFrame(frame);
WriteToOutputQueue(frame);
DWORD time_end = timeGetTime();
DWORD next_frame_time = start_time + ++frame_counter * frame_time;
DWORD time_to_sleep = next_frame_time - time_end;
if (time_to_sleep > 0) {
Sleep(time_to_sleep);
}
}
timeEndPeriod(1);
}
Run Code Online (Sandbox Code Playgroud)
当 CPU 能力充足并且需要更高的保真度和平滑度时,您不仅可以从一帧计算输出帧,还可以通过某种插值计算更多帧(类似于 mpeg 编解码器中使用的技术)。输出帧时间戳与输入帧时间戳越接近,分配给该特定输入帧的权重就越大。